将元素拆分为python中的新列表

时间:2014-11-05 22:09:19

标签: python

我的列表是这样的:

['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']

如何拆分此列表中的元素,并将其分为3个新列表:

[' 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)

谢谢!

3 个答案:

答案 0 :(得分:2)

怎么样:

>>> 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')]

(它给出了一个元组列表而不是列表列表,但是如果你关心它就很容易改变。)

答案 1 :(得分:1)

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]

输出:

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']

答案 2 :(得分:1)

最基本的解决方案,仅供参考:

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