程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python common syntax sugar

編輯:Python

Variable exchange

# Unrecommended
temp = a
a = b
b = temp
# Recommended
a, b = b, a

Chain comparison

# Unrecommended
if grade > 60 and grade < 90:
print("passed")
# Recommended
if 60 < grade < 90:
print("passed")

Three mesh operation

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")

File operations

# Unrecommended
f = open('file.txt', 'w')
f.write("test")
f.close()
# Recommended
with open('file.txt', 'w') as f:
f.write('test')

String splicing

# Unrecommended
list = ['1','2','3','4','5']
str = ""
for item in list:
str += item
# Recommended
str = ''.join(list)

The list of deduction

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)

Built in functions map

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]

Decorator

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved