How to handle unpacking variable length extensions in Python2?

How to handle unpacking variable length extensions in Python2 ?

In Python3, if I have a variable length of subscriptions, I could use this idiom:

>>> x = [(1, 2,3,4,5), (2, 4,6), (3, 5,6,7,8,9)] >>> for i, *item in x: ... print (item) ... [2, 3, 4, 5] [4, 6] [5, 6, 7, 8, 9] 

In Python2, this is an invalid syntax:

 >>> x = [(1, 2,3,4,5), (2, 4,6), (3, 5,6,7,8,9)] >>> for i, *item in x: File "<stdin>", line 1 for i, *item in x: ^ SyntaxError: invalid syntax 

By the way, this question is slightly different from the idiomatic way to unpack a list of variable lengths of maximum size n , where the solution requires knowledge of a fixed length.

And this question is specific to solving the problem in Python2.

+6
source share
4 answers

Python 2 does not have splat ( *item ) syntax. The easiest and most intuitive way is the long way:

 for row in x: i = row[0] item = row[1:] 
+5
source

If you plan to use this design a lot, it might be worth writing a little helper:

 def nibble1(nested): for vari in nested: yield vari[0], vari[1:] 

then you can write your loop

 for i, item in nibble1(x): etc. 

But for some reason I doubt that you will find it elegant enough ...

+2
source

You can also do this:

 x = [(1, 2,3,4,5), (2, 4,6), (3, 5,6,7,8,9)] for lista in x: print (lista[1:]) 

Or using also list comprehension:

 x = [(1, 2,3,4,5), (2, 4,6), (3, 5,6,7,8,9)] new_li = [item[1:] for item in x] 
+1
source

You can try this: -

 x = [(1, 2,3,4,5), (2, 4,6), (3, 5,6,7,8,9)] for item in x: print (list(item[1:])) 
0
source

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


All Articles