我在python中有两个以下结构的列表:
list1 = [[x1,y1],[x2,y2],[x3,y3],[x4,y4],[x5,y5],[x6,y6],[x7,y7],[x8,y8]]
list2 = [1,1,2,2,3,3,3,4]
我想创建一个字典,其中包含第二个列表的键和第一个列表的值,如下所示:
{1: [[x1,y1], [x2,y2]],
2: [[x3,y3], [x4,y4]],
3: [[x5,y5], [x6,y6], [x7,y7]],
4: [x8,y8]}
在python中执行此操作的最有效方法是什么?
我使用了zip命令:
newlist = zip(list2, list1)
但现在我不清楚如何在我想要的字典中对其进行转换。
答案 0 :(得分:0)
不确定这是否是最优化的,但这是一段紧凑的代码:
vals = [["x1","y1"],["x2","y2"],["x3","y3"],["x4","y4"],["x5","y5"],["x6","y6"],["x7","y7"],["x8","y8"]]
keys = [1,1,2,2,3,3,3,4]
result = {}
for k,v in zip(keys,vals):
result[k] = result.get(k, []) + [v]
# output: {1: [['x1', 'y1'], ['x2', 'y2']], 2: [['x3', 'y3'], ['x4', 'y4']], 3: [['x5', 'y5'], ['x6', 'y6'], ['x7', 'y7']], 4: [['x8', 'y8']]}
答案 1 :(得分:0)
如果您不介意使用外部库,那么我建议iteration_utilities.groupedby
(披露:我是该库的作者):
>>> list1= [['x1','y1'],['x2','y2'],['x3','y3'],['x4','y4'],['x5','y5'],['x6','y6'],['x7','y7'],['x8','y8']]
>>> list2 = [1,1,2,2,3,3,3,4]
>>> from iteration_utilities import groupedby
>>> from operator import itemgetter
>>> groupedby(zip(list2, list1), key=itemgetter(0), keep=itemgetter(1))
{1: [['x1', 'y1'], ['x2', 'y2']],
2: [['x3', 'y3'], ['x4', 'y4']],
3: [['x5', 'y5'], ['x6', 'y6'], ['x7', 'y7']],
4: [['x8', 'y8']]}
在幕后它就像使用collections.defaultdict
一样,只是省去了手动迭代。
如果list2
已“排序”,您也可以轻松使用itertools.groupby
:
>>> from itertools import groupby
>>> {key: [i[1] for i in values] for key, values in groupby(zip(list2, list1), itemgetter(0))}
{1: [['x1', 'y1'], ['x2', 'y2']],
2: [['x3', 'y3'], ['x4', 'y4']],
3: [['x5', 'y5'], ['x6', 'y6'], ['x7', 'y7']],
4: [['x8', 'y8']]}