# Unrecommended
temp = a
a = b
b = temp
# Recommended
a, b = b, a
# Unrecommended
if grade > 60 and grade < 90:
print("passed")
# Recommended
if 60 < grade < 90:
print("passed")
Python Trinomial operators... Are not supported ? :
# Unrecommended
if torch.cuda.is_available():
device = torch.device("cuda")
else:
device = torch.device("cpu")
# Recommended
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Unrecommended
f = open('file.txt', 'w')
f.write("test")
f.close()
# Recommended
with open('file.txt', 'w') as f:
f.write('test')
# Unrecommended
list = ['1','2','3','4','5']
str = ""
for item in list:
str += item
# Recommended
str = ''.join(list)
Generate list
# Unrecommended
list = []
for i in range(5):
list.append(i)
# Recommended: List Comprehension
list = [i for i in range(5)]
Filter list elements
# Unrecommended
odd = []
for i in list:
if i % 2 != 0:
odd.append(i)
# Recommended
odd = [i for i in list if i % 2 != 0]
# or
odd = filter(lambda x: x % 2 != 0, list)
Python 2.x Go directly back to the list
>>> def square(x) :
... return x ** 2
>>> map(square, [1, 2, 3, 4, 5])
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])
[1, 4, 9, 16, 25]
Python 3.x Return iterator , Use list() Convert to list
>>> def square(x):
... return x ** 2
>>> map(square, [1, 2, 3, 4, 5])
<map object at 0x100d3d550>
>>> list(map(square, [1, 2, 3, 4, 5]))
[1, 4, 9, 16, 25]
>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))
[1, 4, 9, 16, 25]
def funA(fun):
print("this is A")
fun()
return "this is result"
@funA
def funB():
print("this is B")
if __name__ == "__main__":
print(funB)
# this is A
# this is B
# this is result
Finally, I wish you progress every day !! Study Python The most important thing is mentality . We are bound to encounter many problems in the process of learning , Maybe you can't solve it if you want to break your head . It's all normal , Don't rush to deny yourself , Doubt yourself . If you have difficulties in learning at the beginning , Looking for one python Learning communication environment , Sure Join us , Get the learning materials 、 Discuss together .