将两个具有不同数量值的列表连接到字典

Join two lists with a different amount of values to a dictionary

我有两个不同长度的列表。一个列表具有固定数量的值,这些值稍后将用作键。第二个列表中值的数量可以任意增加。目标是一次又一次地使用第一个列表作为第二个列表的键,这取决于列表“a”获得了多少值。

d = ["a","b","c"]
a = [1,2,3,4,5,6,7]

最后应该是这样的:

c = {"a":1,"b":2,"c":3,"a":4,"b":5,"c"=6,"a":7}

只要“d”中有值,“d”中的键就会针对“a”中的值一次又一次地重复。 谢谢你们。 :)

您可以使用 'cycle from itertools' itertools - cycle 模块来获得您想要的结果。如果你有两个不等长的列表。

from itertools import cycle 

d = ["a","b","c"]
a = [1,2,3,4,5,6,7]
  
# zipping in cyclic if shorter length 
result = dict(zip(a, cycle(d))) 
  
# printing resultant dictionary 
print("resultant dictionary : ", str(result)) 

我同意 Karl Thornton 的观点,字典需要唯一的键。您可以按照 Masud Morshed 的建议进行操作,这是一个很好的解决方案。

但是,如果您的列表 a 不断增加,则您不一定需要字典来实现此功能。你也可以这样写一个函数:

import string
def pseudo_dict(num):
    alphabet = list(string.ascii_lowercase)
    return alphabet[(num - 1)%4]

pseudo_dict(1) -> 'a'