def unpack(obj):
for x in obj:
if isinstance(x, str):
yield x
elif isinstance(x, tuple):
yield from unpack(x)
else:
raise TypeError
x = ('text', ('othertext', ('moretext', ('yetmoretext',))))
result = list(unpack(x))
print(result)
# Python 3.
from collections import abc
def flatten(obj):
for o in obj:
# Flatten any iterable class except for strings.
if isinstance(o, abc.Iterable) and not isinstance(o, str):
yield from flatten(o)
else:
yield o
data = ('a', ('b', 'c'), [1, 2, (3, 4.0)], 'd')
result = list(flatten(data))
assert result == ['a', 'b', 'c', 1, 2, 3, 4.0, 'd']
如果您很高兴递归级别不会变得糟糕(而且您使用的是最新版本的Python):
会给你:
^{pr2}$如果在下一个元组之前有1个以上的字符串,或者直接在元组中有元组,或者在元组之后有字符串等等,也可以很容易地将其修改为与其他类型一起使用,出于谨慎起见,我可能犯了不必要的错误。在
这就是我要做的。这与前面的答案非常相似,但是它在应用程序中更通用,因为它允许除字符串类型对象(即列表和元组)之外的任何类型的iterable被展平,并且它还允许非字符串对象列表的扁平化。在
我自己也找到了答案,我在这里提供给大家参考:
可能不是最干净/最短/最优雅的解决方案,但它很管用,而且看起来很“Python”。在
相关问题 更多 >
编程相关推荐