首页 > 解决方案 > 从具有特定条件的列表列表中创建字典

问题描述

我有一个列表如下:

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。在这种情况下,我需要所有元素配对彼此

标签: pythonpython-3.xlistpython-2.7

解决方案


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'}]

推荐阅读