Python基礎之列表(3)

前兩節說了些列表的基礎操作,今天再所以下內置函數對列表的操作。

直接上乾貨

import random()
x = list(range(11))
random.shuffle(x)
x
#[3,5,8,0,6,9,4,1,2,7,10]

max(x)
#10

max(x, key=str)
#9

sum(x)
#55

len(x)
#11

list(zip(x, [1]*11))                      #多列表元素重新組合
#[(3,1),(5,1),(8,1),(0,1),(6,1),(9,1),(4,1),(1,1),(2,1),(7,1),(10,1)]

list(zip(range(1, 4)))                     #zip()函數也可以用於一個序列或迭代對象
#[(1,),(2,),(3,)]

list(zip(['a','b','c'],[1,2]))
#[('a',1),('b',2)]                             #如果兩個列表不等長,以短的爲準

list(enumerate(x))
#[(0,3),(1,5),(2,8),(3,0),(4,6),(5,9),(6,4),(7,1),(8,2),(9,7),(10,10)]


list(map(str, range(5)))
#['0','1','2','3','4']
def add5(v)
return v+5
list(map(add5, range(10)))
#[5,6,7,8,9,10,11,12,13,14]

def add(x, y):                            #定義add()函數爲元素之和
return x+y
list(map(add, range(5), range(5,10)))     #range(5)和range(5,10)中的各元素相加
#[5,7,9,11,13]

[add(x, y) for x,y in zip(range(5),range(5, 10))]
#[5,7,9,11,13]

列表的向量運算

import random
x = [random.randint(1,100) for i in range(10)]
x
#[55, 59, 6, 94, 22, 39, 88, 7, 95, 72]

list(map(lambda i: i+5, x))                     #所有元素同時加 5
#[60, 64, 11, 99, 27, 44, 93, 12, 100, 77]

x = [random.randint(1,10) for i in range(10)]
x
#[1, 9, 2, 10, 1, 10, 4, 3, 9, 5]

y = [random.randint(1,10) for i in range(10)]
y
#[1, 10, 3, 7, 3, 7, 4, 2, 2, 8]

import operator
sum(map(operator.mul,x , y))                     #向量內積
#320

sum((i*j for i,j in zip(x, y)))                  #使用內置函數計算向量內積
#320

list(map(operator.add, x, y))                    #兩個等長的向量對應元素相加
#[2, 19, 5, 17, 4, 17, 8, 5, 11, 13]

list(map(lambda i,j: i+j, x,y))                  #使用lambda表達式實現同樣效果
#[2, 19, 5, 17, 4, 17, 8, 5, 11, 13]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章