问题:解决如何在python中对表格(二维)进行排序?例如,按照cpu或mem的使用率对top中的进程排序
解决方法:
1. 使用numpy或者panda中的方法对二维矩阵进行操作
2. 使用二维数组(list)存储表格,然后按照某一列排序
下面实现方法二
假设top信息存在于与脚本同目录的txt文件中。具体信息如下:
step1:将文本内容读入list存放
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
lines = []
#read txt file line by line and stored in list
with open('top_info.txt', 'r') as f:
lines = f.readlines()
print(len(lines))
print("initialize arrays:")
lines_len = len(lines) - 7 #info need to process
cols_name = [i for i in lines[6].split()]
arrays = [[0 for i in lines[6].split()] for i in range(lines_len)] #initialize matrix
print(cols_name)
print(len(arrays))
print(*arrays, sep='\n') #print element in multi lines
运行结果:
step2 : 将要处理的几行信息单独存储
#gets into needs to process
for i in range(7, len(lines)):
arrays[i-7] = lines[i].split()
print(arrays[0])
print(arrays[1])
print(arrays[2])
运行结果:
step3 : 按照cpu和mem的使用率排序,降序
关键代码:
from operator import itemgetter
print("sort info:")
#cpu_row = [row[8] for row in arrays]
arrays_sorted_by_cpu = sorted(arrays, key=itemgetter(8), reverse = True)
print(*arrays_sorted_by_cpu, sep='\n')
运行结果:
完整代码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from operator import itemgetter
lines = []
#read txt file line by line and stored in list
with open('top_info.txt', 'r') as f:
lines = f.readlines()
print("the top info in doc is: \n")
print(*lines, sep='\n')
lines_len = len(lines) - 7 #info need to process
arrays = [[0 for i in lines[6].split()] for i in range(lines_len)]
#gets into needs to process
for i in range(7, len(lines)):
arrays[i-7] = lines[i].split()
print("sort info:")
arrays_sorted_by_cpu = sorted(arrays, key=itemgetter(8), reverse = True)
print(*arrays_sorted_by_cpu, sep='\n')
运行结果:
推荐阅读:
知乎:python二维数组按照某一列进行筛选统计?
http://stackoverflow.com/questions/32400639/python-readline
http://stackoverflow.com/questions/5212870/sorting-a-python-list-by-two-criteria
http://stackoverflow.com/questions/4233476/sort-a-list-by-multiple-attributes
http://stackoverflow.com/questions/20183069/how-to-sort-multidimensional-array-by-column
http://stackoverflow.com/questions/2173797/how-to-sort-2d-array-by-row-in-python
http://stackoverflow.com/questions/4183506/python-list-sort-in-descending-order