Reputation:
Here my list is like this:
['Jeoe Pmith H 158.50\n', 'Ppseph Ksdian h 590.00\n', 'll Mos K 89.0\n', 'Wncy Bwn j -97.0\n', 'May KAss S 33.58\n', 'Ai Hami s 670.0\n', 'Age Karn J 674.50\n', 'Loe AIUms s 87000.0\n', 'karl Marx J 67400.9\n', 'Joeh Stig S 34.8\n']
How do it split the element in this list, and make it into 3 new list like this:
[' Jeoe Pmith', 'Ppseph Ksdian', ....'Joeh Stig']
['H' , 'h', 'K', .....'S']
['158.50', '590.00'....'34.8'] #(for this list, getting rid of \n as well)
Thank you !!
Upvotes: 1
Views: 48
Reputation: 323
The most basic solution, just for reference:
lines = ['Jeoe Pmith H 158.50\n', 'Ppseph Ksdian h 590.00\n']
list1 = []
list2 = []
list3 = []
for line in lines:
cleaned = line.strip() # drop the newline character
splitted = cleaned.rsplit(' ', 2) # split on space 2 times from the right
list1.append(splitted[0])
list2.append(splitted[1])
list3.append(splitted[2])
print list1, list2, list3
Upvotes: 1
Reputation: 500953
How about:
>>> l = ['Jeoe Pmith H 158.50\n', 'Ppseph Ksdian h 590.00\n', 'll Mos K 89.0\n', 'Wncy Bwn j -97.0\n', 'May KAss S 33.58\n', 'Ai Hami s 670.0\n', 'Age Karn J 674.50\n', 'Loe AIUms s 87000.0\n', 'karl Marx J 67400.9\n', 'Joeh Stig S 34.8\n']
>>> zip(*(el.rsplit(None, 2) for el in l))
[('Jeoe Pmith', 'Ppseph Ksdian', 'll Mos', 'Wncy Bwn', 'May KAss', 'Ai Hami', 'Age Karn', 'Loe AIUms', 'karl Marx', 'Joeh Stig'), ('H', 'h', 'K', 'j', 'S', 's', 'J', 's', 'J', 'S'), ('158.50', '590.00', '89.0', '-97.0', '33.58', '670.0', '674.50', '87000.0', '67400.9', '34.8')]
(It gives a list of tuples rather than a list of lists, but that's easy to change if you care about it.)
Upvotes: 2
Reputation: 114035
L = ['Jeoe Pmith H 158.50\n', 'Ppseph Ksdian h 590.00\n', 'll Mos K 89.0\n', 'Wncy Bwn j -97.0\n', 'May KAss S 33.58\n', 'Ai Hami s 670.0\n', 'Age Karn J 674.50\n', 'Loe AIUms s 87000.0\n', 'karl Marx J 67400.9\n', 'Joeh Stig S 34.8\n']
L = [s.strip().rsplit(None,2) for s in L]
first = [s[0] for s in L]
second = [s[1] for s in L]
third = [s[2] for s in L]
Output:
In [10]: first
Out[10]:
['Jeoe Pmith',
'Ppseph Ksdian',
'll Mos',
'Wncy Bwn',
'May KAss',
'Ai Hami',
'Age Karn',
'Loe AIUms',
'karl Marx',
'Joeh Stig']
In [11]: second
Out[11]: ['H', 'h', 'K', 'j', 'S', 's', 'J', 's', 'J', 'S']
In [12]: third
Out[12]:
['158.50',
'590.00',
'89.0',
'-97.0',
'33.58',
'670.0',
'674.50',
'87000.0',
'67400.9',
'34.8']
Upvotes: 1