簡體   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