12

15 个提高效率的 Python 编程技巧

 4 years ago
source link: https://www.infoq.cn/article/gGWTBjWt3xHiEQQQMgJa
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

uMFzaaj.jpg!web

每次写 Python 都会忘记该怎么写,最后只能去 Stack Overflow 查?我也一样。时间一长,这让人厌倦。

这 15 个 Python 技巧和窍门,可以帮你提高效率。

1. 交换值

复制代码

x,y=1,2
print(x,y)
x,y=y,x
print(x,y)

2. 字符串列表合并为一个字符串

复制代码

sentence_list = ["my","name","is","George"]
sentence_string =" ".join(sentence_list)
print(sentence_string)

3. 将字符串拆分为子字符串列表

复制代码

sentence_string ="my name is George"
sentence_string.split()
print(sentence_string)

4. 通过数字填充初始化列表

复制代码

[0]*1000# List of1000zeros 
[8.2]*1000# List of10008.2's

5. 字典合并

复制代码

x= {'a':1,'b':2}
y= {'b':3,'c':4}
z= {**x, **y}

6. 反转字符串

复制代码

name ="George"
name[::-1]

7. 从函数返回多个值

复制代码

def get_a_string():
a="George"
b ="is"
c ="cool"
returna, b, c
sentence= get_a_string()
(a, b, c) =sentence

8. 列表解析式

复制代码

a= [1,2,3]
b= [num*2for num in a]# Create a new list by multiplying each element in a by 2

9. 遍历字典

复制代码

m = {'a':1,'b':2,'c':3,'d':4} 
for key,valueinm.items():
print('{0}: {1}'.format(key,value))

10. 同时遍历列表的索引和值

复制代码

m = ['a','b','c','d']
forindex,valueinenumerate(m):
print('{0}: {1}'.format(index,value))

11. 初始化空容器

复制代码

a_list= list()
a_dict= dict()
a_map= map()
a_set= set()

12. 删除字符串两端的无用字符

复制代码

name =" George "
name_2 ="George///"
name.strip()# prints "George"
name_2.strip("/")# prints "George"

13. 列表中出现最多的元素

复制代码

test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test),key= test.count))

14. 检查对象的内存使用情况

复制代码

import sys
x =1
print(sys.getsizeof(x))

15. 将 dict 转换为 XML

复制代码

fromxml.etree.ElementTreeimportElement
defdict_to_xml(tag, d):
'''
Turn a simple dict of key/value pairs into XML
'''
elem = Element(tag)
forkey, valind.items():
child = Element(key)
child.text = str(val)
elem.append(child)
returnelem

英文原文:

15 Python tips and tricks, so you don’t have to look them up on Stack Overflow


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK