下面是我的列表:
['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)谢谢你!!
发布于 2014-11-06 06:16:17
这样如何:
>>> 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')](它给出了一个元组列表,而不是列表列表,但如果您关心它,这很容易更改。)
发布于 2014-11-06 06:13:08
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']发布于 2014-11-06 06:23:13
最基本的解决方案,仅供参考:
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, list3https://stackoverflow.com/questions/26768099
复制相似问题