from collections import defaultdict
INPUT = "/Users/amanshah/Desktop/hsn/a.tcp"
payloads = defaultdict(int)
with open(INPUT) as inf:
for line in inf:
values = line.split()
port = int(values[1])
payload = int(values[5])
payloads[port] += payload
for port in sorted(payloads):
print("{}: {}".format(port, payloads[port]))
text.close()
这里我得到所有端口的输出及其相应的有效载荷(总和)现在我的问题是如何根据有效载荷对端口号进行排序,因为在端口中最大有效载荷应该是第一个???
答案 0 :(得分:2)
根据值而不是键进行排序:
for k, v in sorted(payloads.iteritems(), key=lambda x:x[1], reverse=True):
print("{}: {}".format(k, v))
由于你所做的只是在这里保持计数,你也可以使用collections.Counter
,然后使用它的most_common()
方法:
from collections import Counter
payloads = Counter()
...
for k, v in payloads.most_common():
print("{}: {}".format(k, v))