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


key=['a','b','c','d']
value=[1,2,3,4]
mydict=dict(zip(key,value))
print mydict

輸出結果:

{'a': 1, 'c': 3, 'b': 2, 'd': 4}

也可以用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))
    new_list.append(new_dict)
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 a
dict={}
for item in a:
    dict[item[0]]=[]
    
for item in a:
    dict[item[0]].append(item[1])
    
print dict

輸出:
{'a': [1, 2, 3], 'c': [3], 'b': [1, 2]}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM