Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[(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 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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading