How would you convert a list like this :
["foo",["banana","apple"], "banana", ["peaches","grapes"]]
into
["foo","banana","apple", "banana", "peaches",'grapes"]
I tried:
flat_list = [item for sublist in regular_list for item in sublist]
CodePudding user response:
If the maximum depth of nesting is not too large, you can use recursion to flatten even deeper amount of nesting:
def flatten(a):
if not isinstance(a, list):
yield a
return
for x in a:
yield from flatten(x)
regular_list = ["foo",[[[["banana",[["apple"]]]]]], [[[["banana"]]]], ["peaches","grapes"]]
flat_list = list(flatten(regular_list))
print(flat_list)
Output
['foo', 'banana', 'apple', 'banana', 'peaches', 'grapes']
CodePudding user response:
One approach using a nested list
comprehension could be to check if each element is a list
, and convert it to a list type otherwise:
regular_list = ["foo",["banana","apple"], "banana", ["peaches","grapes"]]
flat_list = [item for sublist in regular_list
for item in (sublist if isinstance(sublist, list) else [sublist])]
print(flat_list)
Result:
['foo', 'banana', 'apple', 'banana', 'peaches', 'grapes']
CodePudding user response:
arr = ["foo", ["banana", "apple"], "banana", ["peaches", "grapes"]]
ans = []
for el in arr:
ans.extend(el) if isinstance(el, list) else ans.append(el)
ans
# ['foo', 'banana', 'apple', 'banana', 'peaches', 'grapes']