Python列表推導式和字典推導式

列表推導式

>>> [x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]

字典推導式

冒號隔開的兩個值分別作爲key和value

>>> squares = {i: " {} squared is {}".format(i, i**2) for i in range(10)}
>>> squares
{0: ' 0 squared is 0', 1: ' 1 squared is 1', 2: ' 2 squared is 4', 3: ' 3 squared is 9', 4: ' 4 squared is 16', 5: ' 5 squared is 25', 6: ' 6 squared is 36', 7: ' 7 squared is 49', 8: ' 8 squared is 64', 9: ' 9 squared is 81'}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章