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]}

 

转载于:https://www.cnblogs.com/wangbin2188/p/6532587.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值