1. 程式人生 > >Python3快速入門——(8)列表生成式(list comprehension)

Python3快速入門——(8)列表生成式(list comprehension)

列表生成式(list comprehension)lis=list(range(1,11)) #lis=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]lis=list(range(10)) #lis=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]L=[]for x in list(range(1,11)): L.append(x*x) #L=[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]#列表生成式m=[x*x for x in range(1,11)]#m=[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
m=[x*x for x in range(1,11) if x%2==0]#[4, 16, 36, 64, 100] 篩選出僅偶數的平方m=[x+y for x in 'ABC'for y in 'abc']#使用兩層迴圈,可以生成全排列print(m) #結果為['Aa', 'Ab', 'Ac', 'Ba', 'Bb', 'Bc', 'Ca', 'Cb', 'Cc']#列出當前目錄下的所有檔案和目錄名,可以通過一行程式碼實現import os #匯入os模組f=[d for d in os.listdir('.')]## os.listdir可以列出檔案和目錄print(f)
#結果為f=['.idea', 'test01.py', 'venv', '__pycache__']#列表生成式也可以使用兩個變數來生成listd = {'x': 'A', 'y': 'B', 'z': 'C' }m=[x+'='+y for x,y in d.items()]#m=['x=A', 'y=B', 'z=C']#把一個list中所有的字串變成小寫L = ['Hello', 'World', 'IBM', 'Apple']m=[s.lower() for s in L]#m=['hello', 'world', 'ibm', 'apple']