简体   繁体   中英

Reversing a nested tuple in Python using the function reversed

I have a tuple and would like to reverse it in Python.

The tuple looks like this : (2, (4, (1, (10, None)))) .

I tried reversing in Python by:

a = (2, (4, (1, (10, None))))
b = reversed(a)

It returns me this:

<reversed object at 0x02C73270>

How do I get the reverse of a ? Or must I write a function to do this?

The result should look like this:

((((None, 10), 1), 4), 2)
def my_reverser(x):
  try:
    x_ = x[::-1]
  except TypeError:
    return x
  else:
    return x if len(x) == 1 else tuple(my_reverser(e) for e in x_)

Try this deep-reverse function:

def deep_reverse(t):
    return tuple(deep_reverse(x) if isinstance(x, tuple) else x 
                 for x in reversed(t))

This will handle arbitrarily nested tuples, not just two-tuples.

As explained in the documentation , the reversed function returns an iterator (hence the <reversed at ...> ). If you want to get a list or a tuple out of it, just use list(reversed(...)) or tuple(reversed(...)) .

However, it's only part of our problem: you'll be reversing the initial object (2, (...)) as (...,2) , while the ... stays the same. You have to implement a recursive reverse: if one element of your input tuple is an iterable, you need to reverse it to.

It does not make sense to do this with reversed , sorry. But a simple recursive function would return what you want:

def reversedLinkedTuple(t):
  if t is None:
    return t
  a, b = t
  return reversedLinkedTuple(b), a

reversed is usable only on reversible iterable objects like lists, tuples and the like. What you are using (a linked list) isn't iterable in the sense of the Python built-in iter .

You could write a wrapping class for your linked list which implements this and then offers a reverse iterator, but I think that would be overkill and would not really suit your needs.

def reverse(x):
    while x >= 0:
        print(x)

x = x = 1
reverse(x)

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