Hey Guys i have a list like
['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81' , '10208, Patrick, Green, 1, 3.95']

i need to split this list and create a list of this form

10015
John
Smith
2
3.01
10334
Jane
Roberts
4
3.81

any ideas how to do it im lost i used the slit() couldnt get it to work

Recommended Answers

All 9 Replies

and create a list of this form

That's not a list,if you want only those item in a new list.

lst = ['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81' , '10208, Patrick, Green, 1, 3.95']
>>> lst[:2]
['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81']

To get the output you show.

>>> new_lst = lst[:2]
>>> for data in new_lst:     
        for item in data.split(', '):
            print item

10015
John
Smith
2
3.01
10334
Jane
Roberts
4
3.81

['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81' , '10208, Patrick, Green, 1, 3.95']
there is the list so i want it like

['10015', 'John', 'Smith', '2', '3.01','10334', 'Jane', 'Roberts', '4', '3.81' , '10208', 'Patrick', 'Green', '1, 3.95']

lst = ['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81' , '10208, Patrick, Green, 1, 3.95'] 
>>> new_lst = []    
>>> for data in lst:
        for item in data.split(','):
            new_lst.append(item)

>>> print new_lst
['10015', ' John', ' Smith', ' 2', ' 3.01', '10334', ' Jane', ' Roberts', ' 4', ' 3.81', '10208', ' Patrick', ' Green', ' 1', ' 3.95']

Ohhhhhhhhhhhhh i had the split function written below the append
Thanks alot for you help

Ok thanks.
If it's a school task deliver this for fun,and ask your teacher to explain it.

>>> sum(map(lambda x: str.split(x, ','), lst), [])
['10015', ' John', ' Smith', ' 2', ' 3.01', '10334', ' Jane', ' Roberts', ' 4', ' 3.81', '10208', ' Patrick', ' Green', ' 1', ' 3.95']

Or try this ...

slist = ['10015, John, Smith, 2, 3.01', '10334, Jane, Roberts, 4, 3.81' , '10208, Patrick, Green, 1, 3.95']

mylist = [item.strip() for s in slist for item in s.split(',')]
print(mylist)

''' result ...
['10015', 'John', 'Smith', '2', '3.01', '10334', 'Jane', 'Roberts', '4', '3.81', '10208', 'Patrick', 'Green', '1', '3.95']
'''

Yes here is list comprehension much better looking,than my (for fun) functional programming style soultion.

Wow snippsat, what does sum() do here?
I thought it would just add up numbers in a list.

>>> lst = [[1,2], [3,4]]
>>> lst
[[1, 2], [3, 4]]
>>> sum(lst, [])
[1, 2, 3, 4]

When use sum() on the outer list and set second argument to an empty list [],default is 0.
Python will concatenate the inner lists,producing a flattened list.
so on the inner list.

>>> [1,2] + [3,4]
[1, 2, 3, 4]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.