Skip to main content
 首页 » 编程设计

python之使用 reversed 函数在 Python 中反转嵌套元组

2025年05月04日12soundcode

我有一个元组,想用 Python 反转它。

元组看起来像这样:(2, (4, (1, (10, None))))。

我尝试通过以下方式在 Python 中进行逆向:

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

它返回给我:

<reversed object at 0x02C73270> 

如何得到a的反转?或者我必须编写一个函数来执行此操作吗?

结果应该是这样的:

((((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_)