I want to remove all nested list inside the nested list. Which means
JavaScript
x
2
1
x = [['-e'], ['-d', ['-e'], '-d'], ['-c', ['-d', ['-e'], '-d'], '-c'], ['-b', ['-c', ['-d', ['-e'], '-d'], '-c'], '-b'], ['-a', ['-b', ['-c', ['-d', ['-e'], '-d'], '-c'], '-b'], '-a']]
2
I want to remove the nested list in index 1,2,3,4… and make it a flat list. To make it clear the below is the separated values in the list.
JavaScript
1
6
1
['-e']
2
['-d', ['-e'], '-d']
3
['-c', ['-d', ['-e'], '-d'], '-c']
4
['-b', ['-c', ['-d', ['-e'], '-d'], '-c'], '-b']
5
['-a', ['-b', ['-c', ['-d', ['-e'], '-d'], '-c'], '-b'], '-a']
6
I want it as
JavaScript
1
8
1
[['-e'], ['-d', '-e', '-d'], ['-c', '-d', '-e', '-d', '-c'], ['-b', '-c', '-d', '-e', '-d', '-c', '-b'], ['-a', '-b', '-c', '-d', '-e', '-d', '-c', '-b', '-a']]
2
3
['-e']
4
['-d', '-e', '-d']
5
['-c', '-d', '-e', '-d', '-c']
6
['-b', '-c', '-d', '-e', '-d', '-c', '-b']
7
['-a', '-b', '-c', '-d', '-e', '-d', '-c', '-b', '-a']
8
And are there any way to get input like above.
JavaScript
1
7
1
for i in range(0,size):
2
z = ['-{}'.format(alnum[size-i])]
3
if alnum[size] != alnum[size-i]:
4
x.append(z*2)
5
else:
6
x.append(z)
7
This was the snippet I used to get that x list.
Advertisement
Answer
With a helper recursive function for flattening nested sublists along with a list comprehension:
JavaScript
1
18
18
1
def nested_flatten(seq):
2
# start with an empty list
3
result = []
4
5
# for each item in the sublist...
6
for item in seq:
7
# is item a list?
8
if isinstance(item, list):
9
# then extend the result with the flattened item
10
result += nested_flatten(item)
11
else:
12
# otherwise extend with the item itself
13
result += [item]
14
return result
15
16
# invoke `nested_flatten` on each sublist
17
out = [nested_flatten(sub) for sub in x]
18
to get
JavaScript
1
8
1
>>> out
2
3
[['-e'],
4
['-d', '-e', '-d'],
5
['-c', '-d', '-e', '-d', '-c'],
6
['-b', '-c', '-d', '-e', '-d', '-c', '-b'],
7
['-a', '-b', '-c', '-d', '-e', '-d', '-c', '-b', '-a']]
8