how to iterate through a list of tuples with lists and group elements sequentially?

Question:

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])]

Answers:

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 zipping 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)]
Answered By: Samwise

using list unpacking and zip method

In [49]: lis = [(0, [75, 1, 30]), (1, [41, 49, 55]), (2, [28, 53, 45])]

In [50]: result = []
    ...: for a, b in lis:
    ...:     res = [a, *b]
    ...:     for i, j in zip(res, res[1:]):
    ...:         result.append((i,j))
    ...: 

In [51]: result
Out[51]: 
[(0, 75),
 (75, 1),
 (1, 30),
 (1, 41),
 (41, 49),
 (49, 55),
 (2, 28),
 (28, 53),
 (53, 45)]

Answered By: sahasrara62

Having fun with itertools…

from itertools import pairwise, chain

lis = [(0, [75, 1, 30]), (1, [41, 49, 55]), (2, [28, 53, 45])]

found = [*chain(*(pairwise(a) for *a, a[1:] in lis))]

print(found)

Attempt This Online!

Answered By: Kelly Bundy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.