如何在 Python 中对 IP 地址和整数进行排序?
我有一个 IP 和整数列表,我希望 python 按第四列排序:
172.2.174.86 172.2.15.65 69694 42272874
172.2.200.100 172.2.15.20 14 4326
10.1.162.12 172.2.15.1 62 4741 170676
172.2.174.86 172.2 .15.64 46021 33956341
10.1.167.237 172.2.15.69 921 133574
问题是Python似乎无法处理同一列表中的IP地址和整数。我只能按字母顺序排序。如何根据第四列的值进行正确排序这是我所拥有的:
lines = open("file.txt", "r").readlines()
lines=[x.split() for x in lines]
for i in lines:
i.reverse()
lines.sort(cmp, reverse=True)
for i in lines:
print i
I have a list of IPs and integers that I'd like to python to sort by the 4th column:
172.2.174.86 172.2.15.65 69694 42272874
172.2.200.100 172.2.15.20 14 4326
10.1.162.12 172.2.15.162 4741 170676
172.2.174.86 172.2.15.64 46021 33956341
10.1.167.237 172.2.15.69 921 133574
The problem is Python can't seem to handle IP addresses and integers in the same list. I can only sort alphabetically. How do I do correct sorting based on the value of the 4th column Here's what I have:
lines = open("file.txt", "r").readlines()
lines=[x.split() for x in lines]
for i in lines:
i.reverse()
lines.sort(cmp, reverse=True)
for i in lines:
print i
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你的ip整数存储在字符串中,对吧?第四列是字符串的一部分?但是你可以做类似的事情
,或者如果你想要更多的控制,你可以定义一个函数,它接受 2 个字符串并确定哪个是最高的,然后传递该函数来对 cmp 参数进行排序
you ip integers are stored in string, right? and the 4th column is part of the string? however you can do something like
or if you want more control, you can define a function that takes 2 string and determine wich is the highest, then pass that func to sort through cmp argument
我认为你不需要改变你的路线。 您应该能够简单地对行进行排序
假设第四列中始终有一个整数值,
。讨论 Python 序列以及如何操作它们的好链接:Effbot
I don't think you need to reverse your lines. You should be able to simply sort the lines using
assuming that you always have an integral value in your fourth column.
Good link discussing Python sequences and how to manipulate them: Effbot
以下是您所追求的吗?
Is the following what you're after?
结果:
the results:
我找不到在没有长复杂函数和 lambda 的 py 中完成此操作的干净简单的方法,
到目前为止最简单的方法,
pip install sh
sh 模块非常棒。
I couldnt find clean easy way to do this in py w/o long complex functions and lambdas,
easiest way by far,
pip install sh
sh module is fantastic.