Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 合并长度不等的列表以形成字典_Python_Python 3.x - Fatal编程技术网

Python 合并长度不等的列表以形成字典

Python 合并长度不等的列表以形成字典,python,python-3.x,Python,Python 3.x,如何将一个列表与另一个长度不等的列表联接到一个字典中 list_header=['a','b'] list_value=[1,2,3,4,5,6,5,7,8] 结果字典: {iteration1:{'a':1,'b':2},“iteration2:{'a':3,'b':4},“iteration3:{'a':5,'b':6},“iteration4:{'a':7,'b':8}更新(基于更改的问题) 您可以使用嵌套字典生成所需的结果: out = { "iteration" + str(i+1)

如何将一个列表与另一个长度不等的列表联接到一个字典中

list_header=['a','b']
list_value=[1,2,3,4,5,6,5,7,8]
结果字典:

{iteration1:{'a':1,'b':2},“iteration2:{'a':3,'b':4},“iteration3:{'a':5,'b':6},“iteration4:{'a':7,'b':8}
更新(基于更改的问题)

您可以使用嵌套字典生成所需的结果:

out = { "iteration" + str(i+1) : { list_header[j] : list_value[i*len(list_header)+j] for j in range(len(list_header)) } for i in range(len(list_value) // len(list_header)) }
print(out)
输出:

{'iteration3': {'b': 6, 'a': 5}, 'iteration2': {'b': 4, 'a': 3}, 'iteration4': {'b': 8, 'a': 7}, 'iteration1': {'b': 2, 'a': 1}}
[('a', 1), ('b', 2), ('a', 3), ('b', 4), ('a', 5), ('b', 6), ('a', 7), ('b', 8)]
原始答案

你不能创建这样的词典;字典键必须是唯一的。不过,您可以创建元组列表:

list_header=['a','b']
list_value=[1,2,3,4,5,6,7,8]

out = [(h, v) for h, v in zip(list_header * (len(list_value) // len(list_header) + 1), list_value)]
print(out)
输出:

{'iteration3': {'b': 6, 'a': 5}, 'iteration2': {'b': 4, 'a': 3}, 'iteration4': {'b': 8, 'a': 7}, 'iteration1': {'b': 2, 'a': 1}}
[('a', 1), ('b', 2), ('a', 3), ('b', 4), ('a', 5), ('b', 6), ('a', 7), ('b', 8)]

你的结果毫无意义;键必须是唯一的,因此输出将是
{'a':7,'b':8}
,之前的值将被覆盖。