a = ['x']
b = ['y', 'z']
我想结合上面的2个列表并创建如下的字典
c = {'x': ['y', 'z']}
我尝试了下面的代码但是没有用
from itertools import cycle
c = dict(zip(a, cycle(b)))
输出:
c = {'x': 'y'}
答案 0 :(得分:0)
a
只包含一个密钥?如果是,请直接创建:
a = ['x']
b = ['y', 'z']
d = {a[0]: b}
print(d)
答案 1 :(得分:0)
您确实需要提供更多详细信息...
如果您希望逐步完成b
对,那么您可以:
>>> a = ['x']
>>> b = ['y', 'z']
>>> x = iter(b)
>>> dict(zip(a, zip(x, x)))
{'x': ('y', 'z')}
但len(a)
必须等于len(b)//2
,或者您可以循环浏览b
:
>>> import itertools as it
>>> a = ['x', 'y', 'z']
>>> b = ['y', 'z']
>>> x = it.cycle(b)
>>> dict(zip(a, zip(x, x)))
{'x': ('y', 'z'), 'y': ('y', 'z'), 'z': ('y', 'z')}
或使用多对b
:
>>> a = ['x', 'y', 'z']
>>> b = ['a', 'b', 'c', 'd']
>>> x = it.cycle(b)
>>> dict(zip(a, zip(x, x)))
{'x': ('a', 'b'), 'y': ('c', 'd'), 'z': ('a', 'b')}
答案 2 :(得分:-1)
这似乎工作正常:
a = ['x']
b = ['y','z']
c = dict(a=b)
print(c)
你有没有理由为Python内置的函数导入循环?
答案 3 :(得分:-1)