I have this list
lis = [(0, [75, 1, 30]), (1, [41, 49, 55]), (2, [28, 53, 45])]
and I’m trying to group these values sequentially together in tuples. What would be a way to do this?
Expected output is
[(0,75), (75, 1), (1, 30), (1, 41), (41,49), (49,55), (2,28), (28, 53), (53, 45)]
found = []
for tup in edge_list:
found.append((tup[0], tup[1][0]))
found.append((tup[1][0], tup[1][1]))
found.append((tup[1][1], tup[1][2]))
print(found)
is there a better/easier approach to iterate over this no matter what the size of the second tuple looks like
[(0, [82, 70, 79, 77, 42]), (1, [40, 61, 58, 66, 69]), (2, [80, 30, 12, 77, 9])]
>Solution :
A useful trick is to flatten out the elements of lis
via the *
operator:
>>> lis = [(0, [75, 1, 30]), (1, [41, 49, 55]), (2, [28, 53, 45])]
>>> [(a, *b) for a, b in lis]
[(0, 75, 1, 30), (1, 41, 49, 55), (2, 28, 53, 45)]
Given any sequence, you can produce the kind of pairing you’re looking for by zip
ping it with an offset version of itself:
>>> list(zip(s, s[1:]))
[(1, 2), (2, 3), (3, 4)]
Combining those two techniques (i.e. taking the sequences within lis
and then converting them into pairs), you can do:
>>> [list(zip((a, *b), b)) for a, b in lis]
[[(0, 75), (75, 1), (1, 30)], [(1, 41), (41, 49), (49, 55)], [(2, 28), (28, 53), (53, 45)]]
and to get them all into a single list of pairs, we can do a nested list comprehension:
>>> [z for a, b in lis for z in zip((a, *b), b)]
[(0, 75), (75, 1), (1, 30), (1, 41), (41, 49), (49, 55), (2, 28), (28, 53), (53, 45)]