简体   繁体   中英

Retrieving values form a nested list

I have a list b which contains the values

(0,3,[(1,0),(0,-1)])

How would I go about iterating through this list so i can get the values from both the outer list and the tuples? My current idea would be to make a variable equal to b[0] and b[1] as this will not expand and it will only hold 2 values. The list of tuples however, can expand so how would i go through the list to get the tuples?.

Thanks for the help.

You can do it by defining a custom method:

b = (0, 3, [(1,0),(0,-1)])

def print_list(l):
    for i in l:
        if isinstance(i, list) or isinstance(i, tuple):
            print_list(i)
        else:
            print i

>>> print_list(b)
0
3
1
0
0
-1

I know, you asked for iterating, but in case, the structure (nested tuple, list and tuple) are of fixed lengths, then you might use unpacking, which allows assigning values to some variable in one step.

>>> data = (0,3,[(1,0),(0,-1)])
>>> a, b, ((x1, y1), (x2, y2)) = data
>>> a
0
>>> b
3
>>> x1
1
>>> y1
0
>>> x2
0
>>> y2
-1

If you are using Python 3.3+ you can do the following:

def flatten(l):
    for i in l:
        if hasattr(i, '__iter__'):
            yield from flatten(i)
        else:
            yield i

Than call the method like:

nested_list = (0,3,[(1,0),(0,-1)])
for i in flatten(nested_list):
    print(i)

In Python version lower than 3.3 you cannot use 'yield from', and instead have to do this:

def flatten(l):
    for i in l:
        if hasattr(i, '__iter__'):
            for i2 in flatten(i):
                yield i2
        else:
            yield i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM