a,b = b,a
-------------------
res = []
for i in range(10):
res.append(i)
代替为
[x for x in range(10)]
-------------------
if x > 3 and y < 2:
do
else:
do
代替为
condition1 = 'x > 3'
condition1 = 'x > 3'
if condition1 and condition2:
do
else:
do
-------------------
for i in range():
代替为
for k,v in enumerate():
-------------------
序列解包
a = 1, b = [2,3]
代替为
a, *b = [1,2,3]
这里着实没看懂
------------------
str = ['a','b','c']
res = ''
for i in str:
res += i
代替为
res = ''.join(str)
------------------
if condition is True / not null:
代替为:
if condition:
------------------
获取字典的元素
dict = {'key':'value'}
dict.get('key')
------------------
a = [1,2,3]
for i in range(len(a)):
a[i] += 1
代替为
a = map(lambda x : x+1,a)
------------------
def func():
x = 1
y = 2
代替为
def func(x=1,y=2):
------------------
占位符 _
------------------
if age > 18 and age < 30:
代替为
if 18 < age < 30:
------------------
if a > 3:
b = 2
else:
b = 1
代替为
b = 2 if a > 3 else 1
------------------
if x == 1 or x == 2
代替为
if x in [1,2]
------------------
dict = {x : x**2 for x in range(3)}
------------------
f = open('file.txt')
lines = f.reads()
f.close()
代替为
with open('file.txt') as f:
lines = f.reads()
------------------
更多的请参考:
https://book.pythontips.com/en/latest/index.html
https://github.com/JeffPaine/beautiful_idiomatic_python
网友评论