我有下一个string
string = 'tuned 1372 root 6u REG 8,3 4096 102029349 /tmp/ffiabNswC (deleted)\ngmain 1372 2614 root 6u REG 8,3 4096 102029349 /tmp/ffiabNswC (deleted)\n'我需要将string的每个元素放入list1[0][..]中,但当我看到新行'\n‘时,我必须将接下来的元素放入list1[1][..]中
多维列表,如下所示:
list1 = [["tuned", "1372", "root", "6u", "REG", "8,3", "4096", "102029349", "/tmp/ffiabNswC", "(deleted)"],
["gmain", "1372", "2614", "root", "6u", "REG", "8,3", "4096", "102029349", "/tmp/ffiabNswC", "(deleted)"]]我用split做了这件事,但它把我都放在了同一个维度上。
发布于 2017-05-30 02:13:39
首先拆分一行(以获得行),然后按空格拆分每个元素(以获得每列):
data = "tuned 1372 root 6u REG 8,3 4096 102029349 /tmp/ffiabNswC (deleted)\ngmain 1372 2614 root 6u REG 8,3 4096 102029349 /tmp/ffiabNswC (deleted)\n"
parsed = [elements.split() for elements in data.strip().split("\n")] # `strip()` removes the last whitespace so we don't get blank elements
print(parsed)
# [['tuned', '1372', 'root', '6u', 'REG', '8,3', '4096', '102029349', '/tmp/ffiabNswC', '(deleted)'], ['gmain', '1372', '2614', 'root', '6u', 'REG', '8,3', '4096', '102029349', '/tmp/ffiabNswC', '(deleted)']]发布于 2017-05-30 02:14:38
以下函数将为您完成此操作:
f = lambda list: [sublist.split(' ') for sublist in list.split('\n')]只要通过f(string)调用即可。
另外,如果你不想在你的子列表中有任何空条目,你可以这样做
f = lambda list: [sublist.split(' ') for sublist in list.split('\n') if sublist]发布于 2017-05-30 02:18:48
输入:-
string = 'tuned 1372 root 6u REG 8,3 4096 102029349 /tmp/ffiabNswC
(deleted)\ngmain 1372 2614 root 6u REG 8,3 4096 102029349 /tmp/ffiabNswC
(deleted)\n'代码:-只需写
mylist=string.split()输出:-
[tuned
1372
root
6u
REG
8,3
4096
102029349
/tmp/ffiabNswC
(deleted)
gmain
1372
2614
root
6u
REG
8,3
4096
102029349
/tmp/ffiabNswC
(deleted)]https://stackoverflow.com/questions/44248313
复制相似问题