【问题标题】:Flattening of nested tuples嵌套元组的展平
【发布时间】:2020-10-04 07:12:08
【问题描述】:

你能像这样展平一个元组吗:

(42, (23, (22, (17, []))))

成为所有元素的一个元组:

(42,23,22,17)

?

【问题讨论】:

标签: python tuples flatten


【解决方案1】:

使用递归的解决方案:

tpl = (42, (23, (22, (17, []))))

def flatten(tpl):
    if isinstance(tpl, (tuple, list)):
        for v in tpl:
            yield from flatten(v)
    else:
        yield tpl

print(tuple(flatten(tpl)))

打印:

(42, 23, 22, 17)

【讨论】:

  • 哇,非常感谢!你能解释一下这是如何工作的吗?我不明白这一行:“if isinstance(tpl, (tuple, list)):”。这里的“元组”是否只是第一个值,所以第一次运行时为 42?
  • @PeterPefi 不,在(42, (23, (22, (17, [])))) 中有很多元组:(42, (23, (22, (17, []))))(23, (22, (17, [])))(22, (17, []))(17, []) 和一个列表:[]isinstance(tpl, (tuple, list)) 只是测试变量 tpl 是否属于 tuplelist 类型
  • 嗯,好吧,所以您可以根据需要将任意数量的类型添加到 isinstance 查询中。
猜你喜欢
  • 2019-03-05
  • 2017-10-10
  • 2012-11-21
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
相关资源
最近更新 更多