Warm tip: This article is reproduced from serverfault.com, please click

python-从具有特定条件的列表列表创建字典

(python - Create a dictionary from a list of lists with certain criteria)

发布于 2020-11-27 20:55:15

我有一个列表列表,如下所示:

l1=[['a1','a2','a3'],['b1','b2'],['c1','a1']]

我想要一个字典列表,如下所示:

[{"start":"a1","end":"ä2"},
 {"start":"a2","end":"a3"},
 {"start":"a3","end":"a1"},
 {"start":"b1","end":"b2"},
 {"start":"c1","end":"a1"}
]

我尝试了以下代码,但索引超出范围异常:

for val in list_listedges:
    for i in range(0,len(val)):
        dict_edges["start"]=val[i]
        dict_edges["end"]=val[i+1]

我正在寻找上述代码的工作解决方案或增强功能,它们将产生相同的结果。此外,3不是固定数字。也可能是4或5.在这种情况下,我需要所有元素与之配对彼此

Questioner
Sam
Viewed
22
martineau 2020-11-28 14:50:37

你可以使用itertools.combinations()函数生成每个子列表中所有可能的点对,从而完全避免编制索引,如下所示:

from itertools import combinations


l1 = [['a1','a2','a3'], ['b1','b2'], ['c1','a1']]

dicts = [{'start': start, 'end': end}
            for points in l1
                for start, end in combinations(points, 2)]

from pprint import pprint
pprint(dicts, sort_dicts=False)

输出:

[{'start': 'a1', 'end': 'a2'},
 {'start': 'a1', 'end': 'a3'},
 {'start': 'a2', 'end': 'a3'},
 {'start': 'b1', 'end': 'b2'},
 {'start': 'c1', 'end': 'a1'}]