python兩個一維list列表合併

2022-07-03 08:27:09 字數 825 閱讀 7759

python兩個一維list列表合併:

list1 = [1,2,3,4]

list2 = [4,5,6,7]

list3 = list1 +list2

print

(list3)#輸出

:[1, 2, 3, 4, 4, 5, 6, 7]

list4 = [list1] +[list2]

print

(list4)#輸出

:[[1, 2, 3, 4], [4, 5, 6, 7]]

#zip() 函式用於將可迭代的物件作為引數,將物件中對應的元素打包成乙個個元組,然後返回由這些元組組成的物件

#這樣做的好處是節約了不少的記憶體。

list5 = [list(t) for t in

zip(list1,list2)]

print

(list5)#輸出

:[[1, 4], [2, 5], [3, 6], [4, 7]]

list6 =list(zip(list1,list2))

print

(list6)

#zip組合後的元素為元組#

輸出:[(1, 4), (2, 5), (3, 6), (4, 7)]

#zip(*)與zip相反,可理解為解壓,返回二維矩陣

a1,a2 = zip(*list6)

print(a1,a2)#輸出

:(1, 2, 3, 4), (4, 5, 6, 7)

print(list(a1),list(a2))#輸出

:[1, 2, 3, 4], [4, 5, 6, 7]

python比較兩個list

自己寫的,耗時很長。當兩個list是100000級別長度的資料時,需要好幾分鐘 if jpg not in list2 paython自帶方法。速度很快 list3 list set3 初始化資料 lista zhangsan lisi wangwu listb zhangsan lisi zhao...

python同時遍歷兩個list

用迭代器迭代的方法也不是不可以,python提供了更直觀的方法 可以使用zip把兩個list打包 類似 list1 1,2,3,4 list2 5,6,7,8 for i1,i2 in zip list1,list2 i3 i1 i2 print i3 用迭代器迭代的方法也不是不可以,python提...

python實現兩個字典合併,兩個list合併

1.兩個字典 a b 合併1 dict a,b 操作如下 a b dict a,b 合併2 dict a.items b.items 如www.cppcns.com下 a b dict a.items b.items 合併3 c c.update a c.update b 輸出c 如下 a b bg...