List comprehensions simplify list looping
"""Quickly generate an include1-20數字的列表"""
list1 = [i for i in range(1,21)]
"""Quickly generate an include1-20之間能被3Divisible list of all numbers"""
list2 = [i for i in range(1,21) if i%3==0]
"""Quickly generate an include1-20之間能被3List of squares of all numbers that are divisible"""
list3 = [i*i for i in range(1,21) if i%3==0]
test = [1,2,3,4,5,6,7,8,9,10]
"""Use a normal loop"""
list1 = []
for i in test:
if i%2==0:
list1.append(i)
"""使用filter"""
list2 = list(filter(lambda i:i%2==0,test))
"""使用列表推導式"""
list3 = [i for i in test if i%2==0]
test = ["1","2","3","4","5","6","7","8","9","10"]
"""Use a normal loop"""
list1 = []
for i in test:
list1.append(int(i))
"""使用filter"""
list2 = list(map(lambda i:int(i),test))
"""使用列表推導式"""
list3 = [int(i) for i in test]
"""Use a normal loop"""
list1 = []
for i in range(1,5):
for j in range(1,i):
if j%2 == 0:
list1.append((i,j))
"""使用列表推導式"""
list2 = [(i,j) for i in range(1,5) for j in range(1,i) if j%2==0]
Dictionary comprehensions simplify dictionary loops
test = {
"a":5,"B":10,"c":15,"D":20}
"""Use a normal loop"""
dict1 = {
}
for k,v in test.items():
dict1[k.upper()] = v
"""使用字典推導式"""
dict2 = {
k.upper():v for k,v in test.items()}
test = {
"a":5,"B":10,"c":15,"D":20}
"""Use a normal loop"""
dict1 = {
}
for k,v in test.items():
if v%2==0:
dict1[k] = v
"""使用字典推導式"""
dict2 = {
k:v for k,v in test.items() if v%2==0}
The ternary operator can simplify selection
格式:exp1 if 條件語句 else exp2
運行過程:if the conditional statement is true,just execute and returnexp1,Otherwise, execute and return exp2
"""簡化前"""
if a>b:
max = a;
else:
max = b;
"""簡化後"""
max = a if a>b else b