目錄python
#普通生成列表 l1 = [] for i in range(10): l1.append(i) print(l1) # 高級的列表推導 l1=[i for i in range(10)] print(l1) l1=[i**2 for i in range(10)] print(l1) # 輸出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
name_list = ['chen', 'python', 'nick', 'rock'] print([name if name == 'chen' else name + 'sb' for name in name_list]) #輸出: ['chen', 'pythonsb', 'nicksb', 'rocksb']