Flatten a lists of list with some lists have multiple values – python
Question:
I was going through this post, which has some great answers, but it does not work for my situation.
I have a list like this:
my_list = [['Hi'],['Hello'],['How', 'are'], ['you']]
I did the flattening and I am getting this,
my_flat_list = [i[0] for i in my_list]
my_flat_list
>>['Hi', 'Hello', 'How', 'you']
If I don’t use i[0]
I get in list format again.
The output I need is:
['Hi', 'Hello', 'How are', 'you']
I also tired this post using itertools
still not getting my desired results.
How can I get my output?
Answers:
You need to join the inner lists:
list(map(" ".join, my_list))
#['Hi', 'Hello', 'How are', 'you']
str.join will help you turn every sublist to a single string:
In [1]: [' '.join(sublist) for sublist in my_list]
Out[1]: ['Hi', 'Hello', 'How are', 'you']
I was going through this post, which has some great answers, but it does not work for my situation.
I have a list like this:
my_list = [['Hi'],['Hello'],['How', 'are'], ['you']]
I did the flattening and I am getting this,
my_flat_list = [i[0] for i in my_list]
my_flat_list
>>['Hi', 'Hello', 'How', 'you']
If I don’t use i[0]
I get in list format again.
The output I need is:
['Hi', 'Hello', 'How are', 'you']
I also tired this post using itertools
still not getting my desired results.
How can I get my output?
You need to join the inner lists:
list(map(" ".join, my_list))
#['Hi', 'Hello', 'How are', 'you']
str.join will help you turn every sublist to a single string:
In [1]: [' '.join(sublist) for sublist in my_list]
Out[1]: ['Hi', 'Hello', 'How are', 'you']