简体   繁体   English

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

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

I have a recursive tuple of strings that looks like this: 我有一个递归的字符串元组,如下所示:

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

(it's actually a tuple of tuples of strings - it's constructed recursively) (它实际上是字符串元组的元组 - 它是递归构造的)

And I'd like to flatten it into a list of strings, whereby foo[1] would contain "text", foo[2] "othertext" and so forth. 我想把它变成一个字符串列表,其中foo [1]将包含“text”,foo [2]“othertext”等等。

How do I do this in Python? 我如何在Python中执行此操作?

The duplicate is about a 2D list of lists, but here I'm dealing with a recursive tuple. 副本是关于列表的2D列表,但在这里我正在处理一个递归元组。

I've found the answer myself, I'll provide it here for future reference: 我自己找到了答案,我会在这里提供以供将来参考:

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

Might not be the cleanest/shortest/most elegant solution, but it works and it seems quite "Pythonic". 可能不是最干净/最短/最优雅的解决方案,但它的工作原理似乎很“Pythonic”。

If you're happy that the level of recursion isn't going to get horrible (and you're using an up to date version of Python): 如果你很高兴递归水平不会变得太可怕(并且你使用的是最新版本的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)

Will give you: 会给你:

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

This will also work if there are more than 1 strings before the next tuple, or if there are tuples directly in tuples, or strings after tuples etc. You can also easily modify it to work with other types if you need, I've probably unnecessarily erred on the side of caution. 如果在下一个元组之前有超过1个字符串,或者在元组中直接有元组,或者在元组之后有字符串等,这也可以工作。如果需要,你也可以轻松修改它以与其他类型一起使用,我可能在谨慎方面不必要地犯了错误。

This is how I would approach it. 这就是我接近它的方式。 This is very similar to a previous answer, however it's more general in application, as it allows any type of iterable to be flattened, except for string-type objects (ie, lists and tuples), and it also allows for the flattening of lists of non-string objects. 这与之前的答案非常相似,但它在应用程序中更为通用,因为它允许任何类型的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