如何将包含列表的混合元组更改为平面元组?

问题描述 投票:0回答:1

我有以下元组:

tuple = ('string1', ['string2', [1,2,3,4]])

我希望它被压平,这样:

tuple = ('string1', 'string2', [1,2,3,4])

我该怎么做?

python tuples
1个回答
0
投票

您无法修改现有类型。所以需要创建一个新的。

array = ('string1', ['string2', [1,2,3,4]])
result = []
for element in array:
    if isinstance(element, list):
        result.extend(element)
    else:
        result.append(element)

print(result)
# ['string1', 'string2', [1, 2, 3, 4]]

final_tuple = tuple(result)

print(final_tuple)
 # ('string1', 'string2', [1, 2, 3, 4])
© www.soinside.com 2019 - 2024. All rights reserved.