0

I have list of list having string of words in following order: I am trying to extract each word from each list as a separate element.

list1=[["Milk,Bread,Butter"],["Milk,Bread,Butter"], ["Milk,Bread,Butter"],]

I used following code

for subList in List1():
    for ele in subList[0].split():
            print (ele) 

Desired output is: Milk, Bread, Butter, Milk, Bread, Butter, Milk, Bread, Butter

However above code produces a complete list: [Milk, Bread, Butter] [Milk, Bread, Butter]

Analyzer
  • 79
  • 7

3 Answers3

1

try:

final = []
for sublist in list1: 
    for item in sublist[0].split(','):
        final.append(item)
mmustafaicer
  • 434
  • 6
  • 15
  • 1
    Thanks! It worked. seems like, I have to check how spilt() function works. Apparently, if there was straight string in the list, e.g., [Milk Butter Bread], then, split() would do the job for me. – Analyzer Aug 11 '22 at 17:43
0

In your example, each sublist in list1 has only one string, so you could simply print the first element:

for sublist in [["Milk,Bread,Butter"],["Milk,Bread,Butter"],["Milk,Bread,Butter"]]:
    print(sublist[0])

If you want them as a single string you could do:

list1 = [["Milk,Bread,Butter"],["Milk,Bread,Butter"], ["Milk,Bread,Butter"]]
res = ",".join([sublist[0] for sublist in list1])
Tomer Ariel
  • 1,397
  • 5
  • 9
0

You can use:

[item for items in [item[0].split(',') for item in list1] for item in items]

output:

['Milk',
 'Bread',
 'Butter',
 'Milk',
 'Bread',
 'Butter',
 'Milk',
 'Bread',
 'Butter']

Or if you can use numpy:

np.ravel([item[0].split(',') for item in list1]).tolist()
SomeDude
  • 13,876
  • 5
  • 21
  • 44