python - 从具有特定条件的列表列表中创建字典
问题描述
我有一个列表如下:
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。在这种情况下,我需要所有元素配对彼此
解决方案
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'}]
推荐阅读
- tensorflow - TensorFlow:恢复的变量似乎是随机的
- azure - 是否可以在 Azure 活动目录中使用自定义证书进行联合单点登录?
- angular - 试图获取 ngbdatepicker 输入值
- python - Python Turtle 图形游戏滞后
- angular - Angular Material 2:在 mat-checkbox 中添加 mat-error
- python - 我试图制作一个输入 N 个数字并确定该数字是否为素数的程序。(必须使用函数)我写了这个:
- apache-kafka - 使用 ThreadPool 消费 Kafka 并不能确保 Ordering?
- python - 在 MAC 10.13 上安装dronekit-sitl
- php - Isset 以 html 形式使用 php 变量
- python - 在 conda 安装 tkinter 后,anaconda 导航器不会启动