Home > Mobile >  How can I join strings that are inside of an element of a multidimensional list?
How can I join strings that are inside of an element of a multidimensional list?

Time:12-31

I have a multidimensional list with strings inside it's elements. For example:

list = [['blur', 'ccd', 'damage', 'jack', 'flare', 'reason'],
        ['jump', 'everyone'],
        ['sadness', 'sick', 'joy']]

And I want join these strings into one element. Something like:

list = [['blur ccd damage jack flare reason'],
        ['jump everyone'],
        ['sadness sick joy']]

I am trying with an for loop, but I get some errors or unexpected results.

CodePudding user response:

The easy way is a list comprehension with str.join:

>>> my_list = [['blur', 'ccd', 'damage', 'jack', 'flare', 'reason'],
...         ['jump', 'everyone'],
...         ['sadness', 'sick', 'joy']]
>>> [' '.join(x) for x in my_list]
['blur ccd damage jack flare reason', 'jump everyone', 'sadness sick joy']
>>> [[' '.join(x)] for x in my_list]
[['blur ccd damage jack flare reason'], ['jump everyone'], ['sadness sick joy']]

CodePudding user response:

You can use that :

list = [['blur', 'ccd', 'damage', 'jack', 'flare', 'reason'],
        ['jump', 'everyone'],
        ['sadness', 'sick', 'joy']]
      

for smallerList in list:
   combinedWord = ""
   for word in smallerList:
      combinedWord = word  " "
   smallerList.clear()
   smallerList.append(combinedWord)
   # print(smallerList)
print(list)
  • Related