如何在Python中将此字符串转换为多维列表?

2024-10-03 00:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下一个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][..]

多维列表,如下图所示:

^{pr2}$

我用split来做,但它把我放在同一个维度上。在


Tags: 元素列表stringrootregtmpsplitlist1
3条回答

在输入:-在

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'

代码:-写下来

^{pr2}$

在输出:-在

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

首先按新行拆分(以获取行),然后按空格拆分每个元素(以获取每个列):

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

以下功能将为您完成此操作:

f = lambda list: [sublist.split(' ') for sublist in list.split('\n')]

只需通过f(string)调用它。在

如果你不想在你的子列表中有任何空的条目,你可以这样做

^{pr2}$

相关问题 更多 >