goe*_*ash -1 python sorting python-3.x
我有一个过程对象列表(用户定义),我想要排序,以便一次获得内存最密集的进程.
但是对排序进行反向排序并不会产生所需的结果.
我的代码:
import psutil as pu
import time
class proc:
def __init__(self,pid,pname,pmem):
self.pid = pid
self.pname = pname
self.pmem = int(pmem)
# def __lt__(self,other):
# return self.pmem<other.pmem
# def __repr__(self):
# return str(self.pmem)+"\t"+self.pname
if __name__ == "__main__":
meg = 1024*1024
gig = meg*1024
while True:
print(pu.cpu_count())
print(pu.cpu_percent())
print("{:.3f} GB".format(pu.virtual_memory().used/gig))
x = []
for p in pu.pids():
pro = pu.Process(pid=p)
# print(pro.memory_info()[0])
# print(pro.memory_info()[1])
x.append(proc(pid=p,pname=pro.name(),pmem=pro.memory_info()[0]))
sorted(x,key=lambda x:x.pmem,reverse=True)
for i in x:
print(str(i.pmem)+'\t'+i.pname)
time.sleep(5)
Run Code Online (Sandbox Code Playgroud)
输出:
您应该使用sort而不是sorted:
x.sort(key=lambda item: item.pmem, reverse=True)
Run Code Online (Sandbox Code Playgroud)
sort对现有清单进行排序; sorted创造一个新的.
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |