简体   繁体   English

如何通过索引合并两个列表

[英]How to merge two lists by index

I have two lists: 我有两个清单:

i = ['a', 'b', 'c']
x = [1,2,3]

i need to produce such dictionary: 我需要制作这样的字典:

xxx = { 'a': [a, 1],
'b': [b, 2],
'c': [c, 3]}

I have done this: 我这样做了:

for indx in i:
    for indx2 in x:
        xxx.update({indx: [indx, indx2]})

but obvioulsy it doesnt work 但是很明显它不起作用

Using dict comprehension: 使用dict理解:

>>> i = ['a', 'b', 'c']
>>> x = [1,2,3]
>>> {key: [key, value] for key, value in zip(i, x)}
{'a': ['a', 1], 'c': ['c', 3], 'b': ['b', 2]}

how about this, if tuple can be the value of your dict. 怎么样,如果元组可以是你的dict的价值。

i= ['a', 'b', 'c']

x= [1, 2, 3]

dict(zip(i,zip(i,x)))
 {'a': ('a', 1), 'b': ('b', 2), 'c': ('c', 3)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM