python遍历多个列表或数组生成字典

本文详细介绍了如何使用Python的zip函数将多个列表转换为字典,包括创建多维列表,模拟数据的行列转换,以及列表的合并与拆分等高级操作技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]}
复制代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值