Reputation: 77
So I want to split a list of lists.
the code is
myList = [['Sam has an apple,5,May 5'],['Amy has a pie,6,Mar 3'],['Yoo has a Football, 5 ,April 3']]
I tried use this:
for i in mylist:
i.split(",")
But it keeps give me error message
I want to get:
["Amy has a pie" , "6" , "Mar 3"]
THis kinds of format
Upvotes: 3
Views: 33654
Reputation: 11
Another way would be:
list(map(lambda x: x[0].split(","), myList))
Upvotes: 1
Reputation: 14313
Here's how you do it. I used an inline for loop to iterate through each item and split them by comma.
myList = [item[0].split(",") for item in myList]
print(myList)
OR You can enumerate to iterate through the list normally, renaming items as you go:
for index, item in enumerate(myList):
myList[index] = myList[index][0].split(",")
print(myList)
OR You can create a new list as you iterate through with the improved value:
newList = []
for item in myList:
newList.append(item[0].split(","))
print(newList)
Upvotes: 5
Reputation: 770
Split each string in sublist :)
new = []
for l in myList:
new.append([x.split(',') for x in l])
print new
Upvotes: 2
Reputation: 11
It's because it's a list of lists. Your code is trying to split the sub-list, not a string. Simply:
for i in mylist:
i[0].split(",")
Upvotes: 1