python遍歷多個列表生成列表或字典

2022-06-12 11:06:09 字數 1515 閱讀 4216

key=['

a','

b','

c','d'

]value=[1,2,3,4]

mydict=dict(zip(key,value))

print mydict

輸出結果:

也可以用zip同時遍歷多個列表,生成乙個多維列表

key=['

a','

b','

c','d'

]value=[1,2,3,4]

other=[5,6,7,8]

print

map(list,zip(key,value,other))

輸出:[['a

', 1, 5], ['

b', 2, 6], ['

c', 3, 7], ['

d', 4, 8]]

多個list組成字典

date=['

2017-01

','2017-02

','2017-03

','2017-04']

c7_list=[1,2,3,4]

c8_list=['

a','

b','

c','d'

]c9_list=['

x','

y','

z','w'

]new_list=

new_dict=

mid=map(list,zip(date,c7_list,c8_list,c9_list))

for item in

mid:

new_dict=dict(zip(['

date

','c7

','c8

','c9

'],item))

print new_list

列表的合併與拆分

in [1]: x=[1,2,3]

in [2]: y=[4,5,6]

in [3]: z=zip(x,y)

in [4]: z

out[4]: [(1, 4), (2, 5), (3, 6)]

in [5]: a,b=zip(*z)

in [6]: a

out[6]: (1, 2, 3)

in [7]: b

out[7]: (4, 5, 6)

通過列表和字典模擬資料的行列轉換

a=[['

a',1],['

a',2],['

a',3],['

b',1],['

b',2],['

c',3]]

print

adict={}

for item in

a: dict[item[0]]=

for item in

a:

print

dict

輸出:

python遍歷多個列表或陣列生成字典

key a b c d value 1,2,3,4 mydict dict zip key,value print mydict 輸出結果 也可以用zip同時遍歷多個列表,生成乙個多維列表 複製 key a b c d value 1,2,3,4 other 5,6,7,8 print map li...

Python同步遍歷多個列表

python的for迴圈十分靈活,使用for迴圈我們可以很輕鬆地遍歷乙個列表,例如 a list z c 1,5,m for each in a list print each 但是,有時遍歷乙個列表並不能滿足我們的需求,在一些特殊的場合,我們可能會需要遍歷兩個甚至多個列表,例如,有兩個列表,第乙個...

Python同步遍歷多個列表

使用python中的zip 函式 zip 函式用於將可迭代的物件作為引數,將物件中對應的元素打包成乙個個元組,然後返回由這些元組組成的列表。如果各個迭代器的元素個數不一致,則返回列表長度與最短的物件相同,利用 號操作符,可以將元組解壓為列表。title user time elements chro...