Python用子串排序字符串数组

标签 python arrays sorting

我有一个数组,其中包含“ps aux”命令的输出。我的目标是使用命令名称列对数组进行排序,但我不知道该怎么做,也找不到答案。

到目前为止,这是我的代码

#!/usr/bin/python
import subprocess

ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')

nfields = len(processes[0].split()) - 1
for row in processes[1:]:
#    print row.split(None, nfields) //This is used to split all the value in the string
     print row

这段代码片段的输出是这样的

...
root        11  0.0  0.0      0     0 ?        S<    2012   0:00 [kworker/1:0H]
root        12  0.0  0.0      0     0 ?        S     2012   0:00 [ksoftirqd/1]
root        13  0.0  0.0      0     0 ?        S     2012   0:00 [migration/2]

...

所以我的目标会有类似的输出,但在最后一列排序,所以最后它看起来像这样

...
root        13  0.0  0.0      0     0 ?        S     2012   0:00 [migration/2]
root        12  0.0  0.0      0     0 ?        S     2012   0:00 [ksoftirqd/1]
root        11  0.0  0.0      0     0 ?        S<    2012   0:00 [kworker/1:0H]
...

你们中有人知道如何执行此操作吗?

最佳答案

像这样:

#!/usr/bin/env python
import subprocess
from operator import itemgetter

ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = [p for p in ps.split('\n') if p]
split_processes = [p.split() for p in processes]

然后像这样打印出你的结果:

for row in sorted(split_processes[1:], key=itemgetter(10)):
    print " ".join(row)

或者像这样(如果你只想要进程名称和参数):

for row in sorted(split_processes[1:], key=itemgetter(10)):
    print " ".join(row[10:])

关于Python用子串排序字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14209064/

相关文章:

iOS coredata排序描述符使用日期的一部分?

python - 在 IPython.display HTML 中用逗号添加千位分隔符

python - 加载序列化 json 对象时出现问题

python - 向 Seaborn 因子图添加简单的误差线

C++ 类模板构造函数——用数组 (U*) 重载引用 (U&) 失败

java - 使用 Java 可序列化保存第二个对象的数组

Android RxJava 记住变量

perl - sort uniq(@stuff) 不排序,不去重

python - Flask View 的流式 shell 输出有效,但永远不会结束

list - 对列表应用自定义排序(对列表列表进行排序)