繁体   English   中英

Python将未知长度的元组(字符串)转换为字符串列表

[英]Python converting a tuple (of strings) of unknown length into a list of strings

我有一个递归的字符串元组,如下所示:

('text', ('othertext', ('moretext', ('yetmoretext'))))

(它实际上是字符串元组的元组 - 它是递归构造的)

我想把它变成一个字符串列表,其中foo [1]将包含“text”,foo [2]“othertext”等等。

我如何在Python中执行此操作?

副本是关于列表的2D列表,但在这里我正在处理一个递归元组。

我自己找到了答案,我会在这里提供以供将来参考:

stringvar = []
while type(tuplevar) is tuple:
        stringvar.append(tuplevar[0])
        tuplevar=tuplevar[1]
stringvar.append(tuplevar)  # to get the last element. 

可能不是最干净/最短/最优雅的解决方案,但它的工作原理似乎很“Pythonic”。

如果你很高兴递归水平不会变得太可怕(并且你使用的是最新版本的Python):

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)

会给你:

['text', 'othertext', 'moretext', 'yetmoretext']

如果在下一个元组之前有超过1个字符串,或者在元组中直接有元组,或者在元组之后有字符串等,这也可以工作。如果需要,你也可以轻松修改它以与其他类型一起使用,我可能在谨慎方面不必要地犯了错误。

这就是我接近它的方式。 这与之前的答案非常相似,但它在应用程序中更为通用,因为它允许任何类型的iterable被展平,除了字符串类型的对象(即列表和元组),它还允许扁平化列表非字符串对象。

# 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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM