I have a list of lists as follows:
l1=[['a1','a2','a3'],['b1','b2'],['c1','a1']]
I want a list of dictionaries as follows:
[{"start":"a1","end":"ä2"},
{"start":"a2","end":"a3"},
{"start":"a3","end":"a1"},
{"start":"b1","end":"b2"},
{"start":"c1","end":"a1"}
]
I have tried the following code and got index out of bounds exception:
for val in list_listedges:
for i in range(0,len(val)):
dict_edges["start"]=val[i]
dict_edges["end"]=val[i+1]
I am looking for a working solution or enhancement of the above code which would yield the same result.Also, 3 is not a fixed number.It could be 4 or 5 also.In that case,I need all the elements to pair up with each other
You can completely avoid indexing by using the itertools.combinations()
function to generate all the possible pairings of the points in each sublist as illustrated below:
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)
Output:
[{'start': 'a1', 'end': 'a2'},
{'start': 'a1', 'end': 'a3'},
{'start': 'a2', 'end': 'a3'},
{'start': 'b1', 'end': 'b2'},
{'start': 'c1', 'end': 'a1'}]
It doesn't work if I have 5 or 4 elements in a list.For example,If I have a list in the list like [a1,a2,a3,a4,a5].The output I get is [{a1,a2},{a2,a3},{a3,a4},{a4,a5},{a5,a1}] but I also need the other connections like [{a1,a3},{a1,a4},{a2,a5},{a2,a5},{a3,a5}].These values are missing @martineau .I need all the values to be paired up
Sam: Oh, OK, now I understand what you want — see updated answer.