开发者

Generic reverse of list items in Python

开发者 https://www.devze.com 2023-02-04 10:37 出处:网络
>>> b=[(\'spam\',0), (\'eggs\',1)开发者_运维知识库] >>> [reversed(x) for x in b]
>>> b=[('spam',0), ('eggs',1)开发者_运维知识库]
>>> [reversed(x) for x in b]
[<reversed object at 0x7fbf07de7090>, <reversed object at 0x7fbf07de70d0>]

Bummer. I expected to get a list of reversed tuples!

Sure I can do:

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

But I hoped for something generic? Smth that when being handed over a list of tuples, returns a list of reversed tuples, and when handed over a list of lists, returns a list of reversed lists.

Sure, an ugly hack with isinstance() is always available but I kind of hoped avoiding going that route.


Extended slicing.

[x[::-1] for x in b]


If you only need depth of one, try [x[::-1] for x in mylist]. Otherwise just make 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

That function actually converts all of the sequences to lists, but you get the gist, I hope.

0

精彩评论

暂无评论...
验证码 换一张
取 消