列表推導式
list = [x*y for x in range(1,5) if x > 2 for y in range(1,4) if y < 3]
集合推導式
a = {x for x in 'abracadabra' if x not in 'abc'}
字典推導式
#key and value 對換
Dict={"name":"ma jun","age":23,"gender":"boy","job":"sales"}
D = {value:key for key,value in Dict.items()}
#{'ma jun': 'name', 23: 'age', 'boy': 'gender', 'sales': 'job'}
List=["America","China","Russia","England","Korea","India"]
Dict={key:value for value,key in enumerate(List)}
#{'America': 0, 'China': 1, 'Russia': 2, 'England': 3, 'Korea': 4, 'India': 5}
函數
dict.items()
#dict.items()用於遍歷字典
dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}
print("result:", dict.items())
print("result: %s"%dict.items())
#for example:
for key,value in dict.items():
print(key,value)
'''
Google www.google.com
Runoob www.runoob.com
taobao www.taobao.com
'''
enumerate() 函數用於將一個可遍歷的數據對象(如列表、元組或字符串)組合爲一個索引序列,同時列出數據和數據下標,一般用在 for 循環當中。
語法:enumerate(sequence, [start=0])
seq = ['one', 'two', 'three']
for i,value in enumerate(seq):
print(i,value)
'''
0 one
1 two
2 three
'''