写代码,优雅性必不可少,能用一行代码解决的是绝不用两行,这里就介绍一些python代码中的奇技淫巧。
- 两个变量互换值
>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a
2
>>> b
1
>>>
- 连续赋值
>>> a = b = c = 60
>>> a
60
>>> c
60
>>>
- 自动解包
>>> a,b,c = [2, 4, 6]
>>> a
2
>>> b
4
>>> c
6
- 链式比较
a = 15
if (10 < a < 20):
print(a)
等价于
a = 15
if (a > 10 and a<20):
print(a)
- 三目运算
href = "wwww.baicu.com"
href = href if "http" in href else "http://"+href
print(href)
等价于
href = "wwww.baicu.com"
if "http" in href:
href = href
else:
href = "http://"+href
print(href)
- 字典合并
>>> a = {'a': 1}
>>> b = {'b':2}
>>> {**a, **b}
{'a': 1, 'b': 2}
>>>
- 列表转字符串
>>> s = ['I', 'love', 'java']
>>> ' '.join(s)
'I love java'
>>>
- 字典推导式
>>> m = {x:x**2 for x in range(0,5)}
>>> m
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>>
- 默认字典值
给字典中的value设置为列表,普通方法
d = dict()
if 'a' not in d:
d['a'] = []
d['a'].append(1)
print(d)
使用defaultdict默认字典构建一个初始值为空列表的字典
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
print(d)
- 赋值表达式
这是3.8的新特性,赋值表达式又成为海象运算符:=, 可以将变量赋值和表达式放在一行,什么意思?看代码就明白
import re
data = "hello031415world"
match = re.search("(\d+)", data) # 3
if match: # 4
num = match.group(1)
else:
num = None
print(num)
等价于
import re
data = "hello031415world"
if match:=re.search("(\d+)", data):
num = match.group(1)
else:
num = None
print(num)
- 列表推导式
>>> list = [x*2 for x in range(10)]
>>> list
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
- 生成器表达式
>>> ge = (x*2 for x in range(10))
>>> ge
<generator object <genexpr> at 0x03B43830>
>>> next(ge)
0
>>> next(ge)
2
>>> next(ge)
4
>>> next(ge)
6
>>> next(ge)
8
>>> next(ge)
10
>>> next(ge)
12
>>> next(ge)
14
>>> next(ge)
16
>>> next(ge)
18
>>> next(ge)
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
StopIteration