I have a double nested list of strings that I need to convert to nested lists of strings. I found some help online but some of the words get lost or the lists become sorted.
new_list = [[['SOCCER'],['-'],['JAPAN'],['GET'],['LUCKY'],['WIN'],[','],['CHINA'],['IN'],
['SURPRISE'],['DEFEAT'],['.']]]
### Expected Result [['SOCCER', '-', 'JAPAN', 'GET', 'LUCKY', 'WIN', ',', 'CHINA', 'IN', 'SURPRISE', 'DEFEAT', '.'], ...
alot = [[ele for ele in sub] for sub in new_list]
outlst = [' '.join([str(c) for c in lst]) for lst in new_list]
CodePudding user response:
One approach is to use chain.from_iterable
:
from itertools import chain
new_list = [[['SOCCER'],['-'],['JAPAN'],['GET'],['LUCKY'],['WIN'],[','],['CHINA'],['IN'],
['SURPRISE'],['DEFEAT'],['.']]]
result = [list(chain.from_iterable(e)) for e in new_list]
print(result)
Output
[['SOCCER', '-', 'JAPAN', 'GET', 'LUCKY', 'WIN', ',', 'CHINA', 'IN', 'SURPRISE', 'DEFEAT', '.']]
Another one is to use nested list comprehension:
result = [[s for lst in e for s in lst] for e in new_list]
CodePudding user response:
Whenever I have a problem with nested or fractals I tend to use recursion.
For this type of challenges the best way to go is to use recursion.
A recursive function is a function which calls itself at some points. To create a recursive function you should follow a 2 step rule:
- Create an exit condition
- Call the function again
Here you can have a function to get each element and check if the element is a list. If it is it would call itself again and extend to an empty list, other wise it would append the non list value to the empty list.
This way you can flatten nested lists no matter the depth.
def flatten(data):
ret = []
for each in data:
if isinstance(each, list):
ret.extend(flatten(each))
else:
ret.append(each)
return ret
Note: Recursion in Python is not what you would want since Python is not good at it. See: Thomas Wouters's answer