【发布时间】:2020-08-11 07:06:54
【问题描述】:
我有一个如下所示的列表:
[[[['one', 'two', 'three']]]]
如何删除外括号以得到["one", 'two', 'three']
这些括号的数量可以是任意的。
【问题讨论】:
我有一个如下所示的列表:
[[[['one', 'two', 'three']]]]
如何删除外括号以得到["one", 'two', 'three']
这些括号的数量可以是任意的。
【问题讨论】:
你有一个单元素、深度嵌套的列表。您可以使用循环将列表重复替换为其第一个元素。当第一个元素不是列表时停止。
lst = [[[['one', 'two', 'three']]]]
while isinstance(lst[0], list):
lst = lst[0]
print(lst)
【讨论】:
您可以搜索包含多个元素或非列表元素的列表。
一种可能性是递归:
def strip_outer(x):
if len(x) != 1 or not isinstance(x[0], list):
return x
return strip_outer(x[0])
我认为您确实不需要为这种迭代创建新的堆栈框架,因此迭代解决方案可能更可取:
def strip_outer(x):
while len(x) == 1 and isinstance(x[0], list):
x = x[0]
return x
【讨论】:
删除列表[[[['one', 'two', 'three']]]]的括号的一种方法是不断检查列表的长度直到它不再是1,然后最终替换原始列表。
def flatten(l):
while len(l) == 1 and type(l[0]) == list:
l = l.pop()
return l
使用给定列表上的函数:
l = [[[['one', 'two', 'three']]]]
l = flatten(l)
print(l)
# Output
# ['one', 'two', 'three']
要使其在多维列表上工作,我们可以使用上面的函数来完成我们的工作,如下所示:
l = [
[[['one', 'two', 'three']]],
[['one', 'two', 'three']],
['one', 'two', 'three']
]
for i in range(len(l)):
l[i] = flatten(l[i])
print(l)
# Output
# [
# ['one', 'two', 'three'],
# ['one', 'two', 'three'],
# ['one', 'two', 'three']
# ]
注意:这种方法专门适用于多维列表。对列表以外的数据类型使用这种方法会导致错误。
【讨论】: