I’ve got an inner nested list as shown below.
test_list = [[['1']], [['2', '2']], [['3', '3'], ['4', '4'], ['5', '5'], ['6', '6']], [['7', '7'], ['8'], ['7'], ['1'], ['7', '7']], [['7', '7'], ['8'], ['7'], ['7', '7']], [['2', '2']]]
I’m not looking out to flatten this list per-say. I would rather like to return a new list which would look like the new_list variable expressed below.
new_list = [['1'], ['2', '2'], [['3', '3'], ['4', '4'], ['5', '5'], ['6', '6']], [['7', '7'], ['8'], ['7'], ['1'], ['7', '7']], [['7', '7'], ['8'], ['7'], ['7', '7']], ['2', '2']]
i.e each item in the new list printed out as:
['1']
['2', '2']
[['3', '3'], ['4', '4'], ['5', '5'], ['6', '6']]
[['7', '7'], ['8'], ['7'], ['1'], ['7', '7']]
[['7', '7'], ['8'], ['7'], ['7', '7']]
['2', '2']
Thanks.
>Solution :
You can use a simple test on the sublists length in a list comprehension:
out = [l[0] if len(l)==1 else l for l in test_list]
output:
[['1'],
['2', '2'],
[['3', '3'], ['4', '4'], ['5', '5'], ['6', '6']],
[['7', '7'], ['8'], ['7'], ['1'], ['7', '7']],
[['7', '7'], ['8'], ['7'], ['7', '7']],
['2', '2']]
If you really want to print:
for l in test_list:
print(l[0] if len(l)==1 else l)
['1']
['2', '2']
[['3', '3'], ['4', '4'], ['5', '5'], ['6', '6']]
[['7', '7'], ['8'], ['7'], ['1'], ['7', '7']]
[['7', '7'], ['8'], ['7'], ['7', '7']]
['2', '2']