python - 按 ip 地址对元组列表进行排序

标签 python

我有一个以 IP 地址作为第一个元素的元组列表

tuple_list = [
    ('192.168.0.15', 33, 60), 
    ('192.168.0.22', 34, 60), 
    ('192.168.0.1', 34, 60), 
    ('192.168.0.2', 34, 60), 
    ('192.168.0.8', 34, 60), 
    ('192.168.0.11', 34, 60)
] 

我想按 IP 地址对其进行排序,但它打印如下:

print(sorted(tuple_list))

[
    ('192.168.0.1', 34, 60), 
    ('192.168.0.11', 34, 60), 
    ('192.168.0.15', 33, 60), 
    ('192.168.0.2', 34, 60), 
    ('192.168.0.22', 34, 60), 
    ('192.168.0.8', 34, 60)
]

当我想要这样的时候:

[
    ('192.168.0.1', 34, 60), 
    ('192.168.0.2', 34, 60), 
    ('192.168.0.8', 34, 60), 
    ('192.168.0.11', 34, 60), 
    ('192.168.0.15', 33, 60), 
    ('192.168.0.22', 34, 60)
]

最佳答案

您可以使用ipaddress模块来存储IP地址而不是字符串。这样它们就可以相互比较,然后使用 operator.itemgetter 进行排序。在我看来,这是最有效的,并且不需要 lambda 表达式来排序。

from ipaddress import IPv4Address
from operator  import itemgetter

tuple_list = [(IPv4Address('192.168.0.15'), 33, 60), (IPv4Address('192.168.0.22'), 34, 60), (IPv4Address('192.168.0.1'), 34, 60), (IPv4Address('192.168.0.2'),34, 60), (IPv4Address('192.168.0.8'), 34, 60), (IPv4Address('192.168.0.11'), 34, 60)]

print(sorted(tuple_list, key=itemgetter(0)))
#[(IPv4Address('192.168.0.1'), 34, 60), (IPv4Address('192.168.0.2'), 34, 60), (IPv4Address('192.168.0.8'), 34, 60), (IPv4Address('192.168.0.11'), 34, 60), (IPv4Address('192.168.0.15'), 33, 60), (IPv4Address('192.168.0.22'), 34, 60)]

我只是使用这个简单的理解将字符串转换为 IPv4Address

[(IPv4Address(x), y, z) for x, y, z in tuple_list]

关于python - 按 ip 地址对元组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57847830/

相关文章:

python - to_sql 引发模糊 KeyError : <class 'numpy.float64' >

python - 使用 pexpect 进行 ssh 密码提示时出现 EOF 异常

Python Popen - 等待与通信与 CalledProcessError

python - kivy.uix.screenmanager.ScreenManagerException : ScreenManager accepts only Screen widget

python - 在 Ubuntu 上 Dockerized Django

python - SQLAlchemy - 映射器配置和声明性基础

python - Redis - 将 CSV 存储为值/blob?

java - python中处理excel文件的最佳库是什么?

python - scipy 和 numpy 规范之间的性能差异

python - 无法在 Python 类中使用方法列表,它会破坏深度复制。解决方法?