用zip把元组或列表生成元组列表,用于动态构造字典
发布时间:2020-02-24 11:47:20
作者:ynkulusi
zip: 取得一个或多个序列为参数,将给定序列中的并排的元素配成元组,返回这些元组的列表 返回并行的元素元组的列表,常用于在for循环中遍历数个序列;zip(*list)逆操作
In [38]: zip("abc","123") 把元组生成元组列表,用于动态构造字典
Out[38]: [('a', '1'), ('b', '2'), ('c', '3')]
In [54]: keys = [1,2,3,4,5]
In [55]: values = ['a','b','c','d','e']
In [56]: d1 = {}
In [57]: for (k,v) in zip(keys,values): d1[k] = v
In [58]: d1
Out[58]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
dict(zip(keys,values))的结果同上
In [38]: a=[1, 2, 3, 4, 5]
In [39]: b=['a', 'b', 'c', 'd', 'e']
In [40]: s={k: i for k,i in zip(a,b)}
In [41]: s
Out[41]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
print {k: i for k,i in zip(a,b)}
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
In [29]: s=[{k: i for k in a} for i in b]
In [30]: s
Out[30]:
[{1: 'a', 2: 'a', 3: 'a', 4: 'a', 5: 'a'},
{1: 'b', 2: 'b', 3: 'b', 4: 'b', 5: 'b'},
{1: 'c', 2: 'c', 3: 'c', 4: 'c', 5: 'c'},
{1: 'd', 2: 'd', 3: 'd', 4: 'd', 5: 'd'},
{1: 'e', 2: 'e', 3: 'e', 4: 'e', 5: 'e'}]
In [44]: s=[{k: i} for k in a for i in b ]
In [45]: s
Out[45]:
[{1: 'a'},
{1: 'b'},
{1: 'c'},
{1: 'd'},
{1: 'e'},
{2: 'a'},
{2: 'b'},
{2: 'c'},
{2: 'd'},
{2: 'e'},
{3: 'a'},
{3: 'b'},
{3: 'c'},
{3: 'd'},
{3: 'e'},
{4: 'a'},
{4: 'b'},
{4: 'c'},
{4: 'd'},
{4: 'e'},
{5: 'a'},
{5: 'b'},
{5: 'c'},
{5: 'd'},
{5: 'e'}]
分类:python
评论数:2
阅读数:1192
-
2020-02-24 13:49:361把列表值按指定key名称(name)加入有相同长度的列表套字典中:
如:
l1=['a', 'b', 'c']
l2=[{'A': '11'}, {'B': '22'}, {'C': '33'}]
for k,v in zip(l1,l2):
v['name']=k
print(l2)值为:
[{'A': '11', 'name': 'a'}, {'B': '22', 'name': 'b'}, {'C': '33', 'name': 'c'}] -
2020-02-24 14:06:172dict(list(zip(['a','b'],[1,2])))
{'a': 1, 'b': 2}