嗨,我尝试使用zip函数将这些列表合并到一个字典中,只显示最后一个数据集。有更好的方法吗
list_values = ['event1','location1','time1','event2','location2','time2','event3','location3','time3','event4','location4','time4']
list_keys = ['event','location','time']
Final desired output dictionary
output = [{'event':'event1','location':'location1','time':'time1'},{'event':'event2','location':'location2','time':'time2'},{'event':'event3','location':'location3','time':'time3'},{'event':'event4','location':'location4','time':'time4'}]
如果我理解您的意思是正确的,您希望通过拆分值列表从两个列表中生成多个词典
您必须为输入数据复制足够多的密钥:
现在您有足够的键来压缩这两个列表。我将把“分块”留给你。:-)
另一种方法是迭代值:
这将获得对应于每个值的键
我们可以使用^{} 来重复这些键。然后我们需要一个列表理解,考虑到关键列表的长度,我们就完成了
更具可读性的方法,采用"chunks" recipe from this StackOverflow answer
最后一次修复。如果我们不想通过使用} 。我只是列出对上一个版本的更改
data = list(zip(cycle(list_keys), list_values))
创建一个列表来消耗内存,那么有一种方法可以从使用zip
得到的iterable中创建块。我们必须为此进口^{相关问题 更多 >
编程相关推荐