Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list of strings by comma

I want to convert

['60,78', '70,77', '80,74', '90,75', '100,74', '110,75']

in to

['60', '78', '70', '77'.. etc]

I thought I could use

for word in lines:
    word = word.split(",")
    newlist.append(word)
return newlist

but this produces this instead:

[['60', '78'], ['70', '77'], ['80', '74'], ['90', '75'], ['100', '74'], ['110', '75']]

Can anyone please offer a solution?

like image 816
GBA13 Avatar asked Dec 15 '22 17:12

GBA13


1 Answers

You need to use list.extend instead of list.append.

newlist = []
for word in lines:
    word = word.split(",")
    newlist.extend(word)  # <----
return newlist

Or, using list comprehension:

>>> lst = ['60,78', '70,77', '80,74', '90,75', '100,74', '110,75']
>>> [x for xs in lst for x in xs.split(',')]
['60', '78', '70', '77', '80', '74', '90', '75', '100', '74', '110', '75']
like image 55
falsetru Avatar answered Jan 04 '23 04:01

falsetru