How to unpack a deeply nested iterative structure

Say, for example, I have a structure that contains many subelements, some of which are structures:

v = [1, 2, 3, [4, (5, 6)]]

How can I unpack them into a series of names that contain only the contents of the structures, not the structure?

The attempt a, b, c, d, e, f = vcalls a ValueError, while using the highlighted expression assigns a structure to the names. How can I unpack them to get:

print(a, b, c, d, e, f)

for print:

1 2 3 4 5 6
+4
source share
2 answers

, () / [] . :

a, b, c, (d, (e, f)) = v
print(a, b, c, d, e, f) 
1 2 3 4 5 6

, , [] :

a, b, c, [d, [e, f]] = v
print(a, b, c, d, e, f) 
1 2 3 4 5 6

, , .

Python v 3 , (d, (e, f)) d, (e, f) .

, dis dis.dis:

dis.dis('a, b, c, (d, (e, f)) = v')
  1           0 LOAD_NAME                0 (v)
              3 UNPACK_SEQUENCE          4      # <- first unpack
              6 STORE_NAME               1 (a)
              9 STORE_NAME               2 (b)
             12 STORE_NAME               3 (c)
             15 UNPACK_SEQUENCE          2      # <- second unpack
             18 STORE_NAME               4 (d)
             21 UNPACK_SEQUENCE          2      # <- third unpack
             24 STORE_NAME               5 (e)
             27 STORE_NAME               6 (f)
             30 LOAD_CONST               0 (None)
             33 RETURN_VALUE

, , (target-list):

v = [1, [2, [3, [4, 5]]]]    
[a, [b, [c, [d, e]]]] = v    
print(a, b, c, d, e)
1 2 3 4 5

[], , , , , .

+10

, , - .

def flatten(container):
    for i in container:
        if isinstance(i, (list,tuple)):
            for j in flatten(i):
                yield j
        else:
            yield i

a, b, c, d, e, f = flatten(v)
+3

Source: https://habr.com/ru/post/1649907/


All Articles