Home > database >  Split The Second String of Every Element in a List into Multiple Strings
Split The Second String of Every Element in a List into Multiple Strings

Time:10-21

I am very very new to python so I'm still figuring out the basics.

I have a nested list with each element containing two strings like so:

mylist = [['Wowza', 'Here is a string'],['omg', 'yet another string']]

I would like to iterate through each element in mylist, and split the second string into multiple strings so it looks like:

mylist = [['wowza', 'Here', 'is', 'a', 'string'],['omg', 'yet', 'another', 'string']]

I have tried so many things, such as unzipping and

for elem in mylist:

     mylist.append(elem)

     NewList = [item[1].split(' ') for item in mylist]
print(NewList)

and even

for elem in mylist:
        
   NewList = ' '.join(elem)
   def Convert(string):
       li = list(string.split(' '))
       return li 
   
   print(Convert(NewList))

Which just gives me a variable that contains a bunch of lists

I know I'm way over complicating this, so any advice would be greatly appreciated

CodePudding user response:

You can use list comprehension

mylist = [['Wowza', 'Here is a string'],['omg', 'yet another string']]
req_list = [[i[0]]  i[1].split() for i in mylist]
# [['Wowza', 'Here', 'is', 'a', 'string'], ['omg', 'yet', 'another', 'string']]

CodePudding user response:

I agree with @DeepakTripathi's list comprehension suggestion ( 1) but I would structure it more descriptively:

>>> mylist = [['Wowza', 'Here is a string'], ['omg', 'yet another string']]
>>> newList = [[tag, *words.split()] for (tag, words) in mylist]
>>> print(newList)
[['Wowza', 'Here', 'is', 'a', 'string'], ['omg', 'yet', 'another', 'string']]
>>> 

CodePudding user response:

You can use the operator on lists to combine them:

a = ['hi', 'multiple words here']
b = []
for i in a:
   b  = i.split()
  • Related