Common inverse list item in Python

>>> b=[('spam',0), ('eggs',1)] >>> [reversed(x) for x in b] [<reversed object at 0x7fbf07de7090>, <reversed object at 0x7fbf07de70d0>] 

Bummer. I was expecting a list of reverse tuples!

Of course I can do:

 >>> [tuple(reversed(x)) for x in b] [(0, 'spam'), (1, 'eggs')] 

But was I hoping for something in common? Smth, that, passing a list of tuples, returns a list of reverse tuples, and when transmitting a list of lists, returns a list of inverted lists.

Of course, an ugly hack with isinstance () is always available, but I seem to be hoping to avoid this route.

+4
source share
2 answers

Extended slicing .

 [x[::-1] for x in b] 
+8
source

If you only need depth, try [x [:: - 1] for x in my list]. Otherwise, just create a recursive function like

 import collections def recursive_reversed(seq): if isinstance(seq, collections.Sequence): return [recursive_reversed(x) for x in reversed(seq)] return seq 

This function actually converts all the sequences into lists, but in fact you get the gist.

0
source

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


All Articles