繁体   English   中英

Python清单中的IP反转

[英]IP reversing in Python List

我正在尝试在Python列表中执行IP的IP反转。

对于反向IP,我将列表中的项目转换为字符串并执行相同的操作。

但是不幸的是我没有得到预期的结果。

考虑具有IP的列表,如下所示:

['1.3.6.5', '8.9.25.4']

预期的相反结果:

 ['5.6.3.1', '4.25.9.8']

获得相反的结果:

4.25.9.5, 8.6.3.1

这是我的代码所附:

        ips = [''.join(ip) for ip in ips if ip]

        def reverse(ips):
                if len(ips) <= 1:
                        return ips
                l = ips.split('.')
                return '.'.join(l[::-1])

        ips = str(ips).strip('[]')
        ips = ips.replace("'", "")

        ip_reversed = reverse(ips)
        LOG.info(ip_reversed)

有人让我知道如何解决此问题,其他人让我知道任何针对此问题的简单解决方案。

使用list_comprehension。 那是,

  • 遍历每个元素

  • 按点分割

  • 然后反转获得的列表

  • 现在,用点加入他们。

     >>> s = ['1.3.6.5', '8.9.25.4'] >>> ['.'.join(i.split('.')[::-1]) for i in s] ['5.6.3.1', '4.25.9.8'] 
ipList = ['1.3.6.5', '8.9.25.4' , '192.168.0.125']

for ip in ipList:
  # '192.168.0.125'(ip)=> ['192','168','0','125'](split)=> ['125'.'0'.'168'.'192'](split)[::-1]
  ip_reverse = '.'.join(ip.split('.')[::-1])
  print(ip_reverse)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM