【问题标题】:Sort one list based on other根据另一个列表对一个列表进行排序
【发布时间】:2021-02-12 20:06:45
【问题描述】:

我有以下两个列表:

list_ip = [10.100.1.100, 10.100.1.30, 10.100.1.110, 10.100.1.40]
list_host = [host1, host2, host3, host4]

我需要的是根据list_ip 上的 IP 地址排序对 list_host 进行排序。

预期输出:

[host2, host4, host1, host3]

我该如何开始?我可以使用哪个功能?

【问题讨论】:

    标签: python-3.x sorting arraylist ip-address


    【解决方案1】:

    对于排序,您可以将 2 个列表压缩在一起,将键作为元组中的第一个元素,然后从排序结果中打印第二个元素

    如果您只使用 10.100.1.x,那么您只需提取 x(通过 split & int 转换)作为键。如果您正在处理许多不同的子网,是的,您需要转换为 ipaddress.IPV4Address 对象,这些对象自然按数值而不是字符串表示排序。

    print([y[1] for y in sorted(zip([int(x.split('.')[-1]) for x in list_ip],list_host))])
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
    • 非常感谢。有没有办法用 python ipaddress 包编写排序函数?
    猜你喜欢
    • 2018-11-15
    • 1970-01-01
    • 2023-04-01
    • 2021-05-02
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    相关资源
    最近更新 更多