【发布时间】:2020-10-04 07:12:08
【问题描述】:
你能像这样展平一个元组吗:
(42, (23, (22, (17, []))))
成为所有元素的一个元组:
(42,23,22,17)
?
【问题讨论】:
-
这能回答你的问题吗? Flatten an irregular list of lists
你能像这样展平一个元组吗:
(42, (23, (22, (17, []))))
成为所有元素的一个元组:
(42,23,22,17)
?
【问题讨论】:
使用递归的解决方案:
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)
【讨论】:
(42, (23, (22, (17, [])))) 中有很多元组:(42, (23, (22, (17, []))))、(23, (22, (17, [])))、(22, (17, []))、(17, []) 和一个列表:[]。 isinstance(tpl, (tuple, list)) 只是测试变量 tpl 是否属于 tuple 或 list 类型