1. 程式人生 > 其它 >(Python基礎語法)列表推導式的應用

(Python基礎語法)列表推導式的應用

列表推導式的應用


列表推導式的語法

在這裡插入圖片描述

應用舉例

print("列表推導式的應用1:二維列表<==>一維列表")

vec = [[1,2,3],[4,5,6],[7,8,9]]#1.二維列表==>一維列表
newlist = [num for elem in vec for num in elem]
print(newlist)

#上述等價形式1:迴圈輸出
vec = [[1,2,3],[4,5,6],[7,8,9]]
result = []
for elem in vec:
	for num in elem:
		result.
append(num) print(result) #上述等價形式2:sum函式降維 vec = [[1,2,3],[4,5,6],[7,8,9]] newlist = sum(vec,[]) print(newlist) #疑問:為什麼可以這樣子呢?這是與sum函式的第二個引數相關的 '''sum(iterable, start=0, /) Return the sum of a 'start' value (default: 0) plus an iterable of numbers When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may reject non-numeric types. ''' #其中start引數意思是,將start依次與可迭代物件中的所有元素相加,然後返回,顯然的我們知道, #[] + [1,2,3] + …… 實現了降維的功能 #上述等價形式3: vec = [[1,2,3],[4,5,6],[7,8,9]] from itertools import chain newlist = list(chain(*vec)) print(newlist)
''' chain(*iterables) --> chain object | | Return a chain object whose .__next__() method returns elements from the | first iterable until it is exhausted, then elements from the next | iterable, until all of the iterables are exhausted. ''' print("\n列表推導式的應用2:列表推導式<==>迴圈結構") alist = [x*x for x in range(10)]#2.列表推導式<==>迴圈結構 print(alist) #上述等價形式1 alist = [] for x in range(10): alist.append(x*x) print(alist) #上述等價形式2 alist = list(map(lambda x:x*x,range(10))) print(alist) print("\n列表推導式的應用3:列出當前資料夾下所有Python檔案") import os alist = [filename for filename in os.listdir('.') if filename.endswith(('.py','.pyw'))] print(alist) ''' endswith(...) S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. ''' ''' listdir(path=None) Return a list containing the names of the files in the directory. path can be specified as either str or bytes. If path is bytes, the filenames returned will also be bytes; in all other circumstances the filenames returned will be str. If path is None, uses the path='.'. On some platforms, path may also be specified as an open file descriptor;\ the file descriptor must refer to a directory. If this functionality is unavailable, using it raises NotImplementedError. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory. ''' print("\n列表推導式的應用4:過濾掉不符合條件的元素") alist = [-1,-4,1,3,4,5,6,-9] newlist = [i for i in alist if i > 0] print(newlist) print("\n列表推導式的應用5") scores = {"Zhang San": 45, "Li Si": 78, "Wang Wu": 40, "Zhou Liu": 96,"Zhao Qi": 65, "Sun Ba": 90, "Zheng Jiu": 78, "Wu Shi": 99,"Dong Shiyi": 60} highest = max(scores.values()) lowest = min(scores.values()) average = sum(scores.values())*1.0/len(scores) print("最高分:",highest,"最低分:",lowest,"平均分:",average) highestPerson = [name for name,score in scores.items() if score == highest] print(highestPerson) ''' values(...) D.values() -> an object providing a view on D's values ''' print("\n列表推導式的應用6:實現多序列元素的任一組合") list1 = [(x, y) for x in range(3) for y in range(3)] list2 = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] print(list1) print(list2) print("\n列表推導式的應用7:生成100以內的所有素數") primelist = [p for p in range(2,100) if 0 not in [p%d for d in range(2,int(p**0.5) + 1)]] print(primelist) ''' if 0 not in [p%d for d in range(2,int(p**0.5) + 1)]: 素數條件,即在[0,aqrt(p)]之間的整數可以 找到p的因子,那麼p%d組成的列表中就有0 ''' print("\n列表推導式的應用8:檔案物件的迭代") with open('C:\\Users\\Nasir\\Desktop\\source code\\Python\\123.txt','r',encoding = 'utf-8') as fp: print([line for line in fp]) print("\n列表推導式的應用9:實現矩陣轉置") matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] newlist = [[row[i] for row in matrix] for i in range(4)] print(newlist) #上述等價實現形式:序列解包 newlist = list(zip(*matrix)) print(newlist) print("\n列表推導式的應用10:列表推導式使用函式or複雜表示式") def f(v): if v%2 == 0: v = v ** 2 else: v = v + 1 return v newlist1 = [f(v) for v in [2,3,4,-1] if v > 0] newlist2 = [v**2 if v%2 == 0 else v+1 for v in [2,3,4,-1] if v>0] print(newlist1) print(newlist2) newlist3 = [item>5 for item in range(10)] print(newlist3)