[英]Remove unnecessary layers from multi-demensional list python
My plan is to turn the input of a multidimensional list with an unknown amount of layers ie [["a"], [["b"], ["c"]]]
into ["a", ["b", "c"]]
but currently my output is the same as the original with the below function:我的计划是将具有未知层数的多维列表的输入,即
[["a"], [["b"], ["c"]]]
变成["a", ["b", "c"]]
但目前我的输出与具有以下功能的原始输出相同:
def extract(tree):
for x in range(len(tree)):
if type(tree[x]) == list:
extract(tree[x])
else:
tree = tree[x]
Basically, I want to remove any unnecessary layers in the array that have only one element,基本上,我想删除数组中只有一个元素的任何不必要的层,
Any ideas on what I'm doing wrong?关于我做错了什么的任何想法?
Thanks for any help谢谢你的帮助
Maybe something like:也许是这样的:
def tree(element):
if isinstance(element, str):
return element
elif len(element) == 1:
return element[0]
unfolded = []
for each in element:
unfolded.append(tree(each))
return unfolded
a = [["a"], [["b"], ["c"]]]
print(tree(a)) # => ['a', ['b', 'c']]
Just add a few returns and your code works just fine.只需添加一些返回值,您的代码就可以正常工作。
def extract(tree):
for x in range(len(tree)):
if type(tree[x]) == list:
tree[x] = extract(tree[x])
else:
return tree[x]
return tree
# test cases
test = [["a"], [["b"], ["c"]]]
print(extract(test))
test = [["a"], [["b"], ["c"], [["b"], ["c"]]]]
print(extract(test))
Not exactly sure what you're trying to accomplish with this code.不完全确定您要使用此代码完成什么。 Axe319's answer will remove all the inner arrays/lists and return both
[["a"], [["b"], ["c"]]]
and ["a", ["b", "c"]]
as ['a','b','c']
. Axe319 的答案将删除所有内部数组/列表并返回
[["a"], [["b"], ["c"]]]
和["a", ["b", "c"]]
如['a','b','c']
。 If you wish to make a list of one, then two, then three etc. (ie. [['a'], ['b', 'c'], ['d', 'e', 'f']...
), you'll have to redesign your code.如果你想列出一个,然后是两个,然后是三个等等(即
[['a'], ['b', 'c'], ['d', 'e', 'f']...
),你必须重新设计你的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.