0

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?

user9431057
  • 1,203
  • 1
  • 14
  • 28
  • 2
    Looks like you want `[' '.join(i) for i in my_list]` – user3483203 Jul 06 '18 at 21:38
  • @Poshi, Nope, not a dupe of that. – DYZ Jul 06 '18 at 21:40
  • @DyZ Question, how did you search that SO post? I have been Googling, did not find any related to my situation, then I posted this question. Is there a trick? May be always use a keyword involved? or anything else? – user9431057 Jul 06 '18 at 21:46
  • 2
    @user9431057 I found that dupe by googling "How to join sublists of strings in python". While yes, this ends up flattening the list, most list flattening questions don't join elements of the sublists, which is why you wouldn't have been able to find it. – user3483203 Jul 06 '18 at 21:49
  • @user3483203 Okay, in the beginning I had no idea that it needs a join. I have been googling 'how to flatten lists' :(. Thank for the comment, love to learn with you all :) – user9431057 Jul 06 '18 at 21:51
  • 1
    Happy to help. You asked a good question with all the necessary information, so keep it up! – user3483203 Jul 06 '18 at 21:53
  • There are two steps to the problem, and each is a common duplicate. `' '.join` can join a list of strings; apply that to each list in the list of lists. – Karl Knechtel Sep 06 '22 at 04:50

2 Answers2

2

You need to join the inner lists:

list(map(" ".join, my_list))
#['Hi', 'Hello', 'How are', 'you']
DYZ
  • 55,249
  • 10
  • 64
  • 93
1

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']
Eugene Primako
  • 2,767
  • 9
  • 26
  • 35