简体   繁体   中英

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:

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))
  1. It's generally good to use isinstance() instead of type() for type checking in code.

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'] . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM