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

2024-10-05 10:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

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

复制是关于一个2D列表的,但是这里我要处理的是递归元组。在


Tags: 字符串text列表foo元组othertextmoretextyetmoretext
3条回答

如果您很高兴递归级别不会变得糟糕(而且您使用的是最新版本的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)

会给你:

^{pr2}$

如果在下一个元组之前有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']

我自己也找到了答案,我在这里提供给大家参考:

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

可能不是最干净/最短/最优雅的解决方案,但它很管用,而且看起来很“Python”。在

相关问题 更多 >

    热门问题