1. 程式人生 > >Python基礎課:內置函數對列表的操作

Python基礎課:內置函數對列表的操作

表的操作 logs 轉換 obj pre object 列表 bject div

 1 >>> x = list(range(10))
 2 >>> import random
 3 >>> random.shuffle(x)  #打亂順序
 4 >>> x
 5 [2, 4, 5, 9, 3, 7, 8, 0, 6, 1]
 6 >>> max(x)  #返回最大值
 7 9
 8 >>> min(x)  #返回最小值
 9 0
10 >>> sum(x)  #所有元素之和
11 45
12 >>> len(x)  #所有元素個數
13
10 14 >>> list(zip(x,[1]*10)) #多列表重新組合 15 [(2, 1), (4, 1), (5, 1), (9, 1), (3, 1), (7, 1), (8, 1), (0, 1), (6, 1), (1, 1)] 16 >>> list(zip(range(1,4))) #zip()函數可以用於一個序列或者叠代對象 17 [(1,), (2,), (3,)] 18 >>> list(zip([a,b,c],[1,2])) #兩個列表不等長,以短的為準 19 [(a, 1), (b, 2)]
20 >>> enumerate(x) #枚舉列表元素,返回enumerate對象 21 <enumerate object at 0x0000016166A057E0> 22 >>> list(enumerate(x)) #enumerate對象可叠代 23 [(0, 2), (1, 4), (2, 5), (3, 9), (4, 3), (5, 7), (6, 8), (7, 0), (8, 6), (9, 1)] 24 >>> x 25 [2, 4, 5, 9, 3, 7, 8, 0, 6, 1]
 1 >>> list(map(str,range(5))) #
轉換為字符串 2 [0, 1, 2, 3, 4] 3 >>> def add5(v): 4 return v+5 5 6 >>> list(map(add5,range(10))) #將單參數函數映射到所有元素 7 [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 8 >>> def add(x,y): 9 return x+y 10 11 >>> list(map(add,range(5),range(5,10))) #將雙參數函數映射到兩個序列上 12 [5, 7, 9, 11, 13] 13 >>> list(map(lambda x,y:x+y, range(5), range(5,10))) 14 [5, 7, 9, 11, 13] 15 >>> [add(x,y) for x, y in zip(range(5), range(5,10))] 16 [5, 7, 9, 11, 13] 17 >>>

Python基礎課:內置函數對列表的操作