记录些自己日常写Python的一些小技巧,算不上高级但代码看起来 Pythonic 一点。
列表推导式
>>> [ i for i in range(10) ]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
字典推导式(Python2.x不支持)
>>> { i:i*i for i in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
集合推导式(Python2.x不支持)
>>> a = {1,3,3,4,5}
>>> {i*2 for i in a}
{8, 2, 10, 6}
字典合并(Python2.x不支持)
>>> a = {'a':1,'b':2}
>>> c = {'c':3, 'd':4}
>>> {**a, **c}
{'a': 1, 'd': 4, 'c': 3, 'b': 2}
反转列表
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
变量交换
>>> a, b = 1, 2
>>> a, b = b, a
变量拆包(Python2.x不支持)
>>> a, *b, c = 1,2,3,4,5
>>> a
1
>>> b
[2, 3, 4]
>>> c
5
>>>
链式比较
>>> if a > 2 and a < 5:
... pass
...
>>> if 2<a<5:
... pass
yield from(区别于yield后面可以加可迭代对象)(Python2.x不支持)
# 使用yield
# 字符串
astr='ABC'
# 列表
alist=[1,2,3]
# 字典
adict={"name":"wangbm","age":18}
# 生成器
agen=(i for i in range(4,8))
def gen(*args, **kw):
for item in args:
for i in item:
yield i
new_list=gen(astr, alist, adict, agen)
print(list(new_list))
# ['A', 'B', 'C', 1, 2, 3, 'name', 'age', 4, 5, 6, 7]
# 使用yield from
# 字符串
astr='ABC'
# 列表
alist=[1,2,3]
# 字典
adict={"name":"wangbm","age":18}
# 生成器
agen=(i for i in range(4,8))
def gen(*args, **kw):
for item in args:
yield from item
new_list=gen(astr, alist, adict, agen)
print(list(new_list))
# ['A', 'B', 'C', 1, 2, 3, 'name', 'age', 4, 5, 6, 7]
两种方式对比,可以看出,yield from后面加上可迭代对象,可以把可迭代对象里的每个元素一个一个的yield出来,对比yield来说代码更加简洁,结构更加清晰。
in代替or
>>> a = 1
>>> if a == 1 or a == 2 or a == 3:
... pass
...
>>> if a in (1,2,3):
... pass
字典代替elif
def fun(x):
if x == 'a':
return 1
elif x == 'b':
return 2
else:
return None
def fun(x):
return {"a": 1, "b": 2}.get(x)
枚举
>>> a = ["a","b","c"]
>>> for i in enumerate(a):
... i
...
(0, 'a')
(1, 'b')
(2, 'c')
生成器
>>> a = ( i for i in range(10)) # 注意区分列表推导式
>>> a
<generator object <genexpr> at 0x10189aca8>
>>> for i in a:
... i
...
0
1
2
3
4
5
6
7
8
9
计算列表中出现次数最多元素
>>> a = [1,1,2,3,4,5,6,7,8]
>>> max(set(a), key=a.count)
1
>>> from collections import Counter
>>> Counter().most_common()[0][0]
1
判断对象类型
>>> isinstance(a,(str,int,list))
True
__str__ 与 __repr__
>>> import datetime
>>> str(datetime.datetime.now())
'2019-03-11 16:30:10.129306'
>>> repr(datetime.datetime.now())
'datetime.datetime(2019, 3, 11, 16, 30, 47, 165859)'
__str__是面向用户的,而__repr__面向程序员