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

2024-06-30 08:05:43 发布

您现在位置: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)

谢谢你


Tags: 列表mayaillmosbwnstigwncy
3条回答

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

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

怎么样:

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

(它给出的是一个元组列表,而不是一个列表,但是如果您关心它,这很容易更改。)

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

相关问题 更多 >