【问题标题】:How can I reorganize this list?如何重新组织此列表?
【发布时间】:2019-05-20 08:13:03
【问题描述】:

我等待服务器向我发送一个列表,其中包括 ip 后跟“,”后跟端口,后跟“;”然后是另一个元组......还有另一个和 x 元组......

例子是:

127.0.0.1,45403;127.0.0.1,47146;127.0.0.1,52888

我想重新组织它,所以我在每个循环中都有 x 迭代

Ipx = 127.0.0.1 
Portx = 45403

在循环的下一次迭代中

Ipx = 17.0.0.1
Portx = 47146

每个元组的等(Ipx 和 Portx 是不同的变量)

我试过了

ipx , portx = lista.split(";")
        print ipx
        print portx

但它不起作用......

【问题讨论】:

  • 如果您展示了您尝试过的内容,您将在此板上获得更多帮助。我建议使用split,就像你标记的那样。例如,list_of_ips = string_of_ips.split(";") 会让你走到一半。
  • @malan 并不是我想要的……我只是想在不同的变量中获取每个 ip 和端口。谢谢

标签: python string list split ip


【解决方案1】:

你需要用 ; 分割然后按 ,如下:

lista = "127.0.0.1,45403;127.0.0.1,47146;127.0.0.1,52888"

for address in lista.split(";"):
    ipx, portx = address.split(',')
    print(f'IP: {ipx}, Port: {portx}')

【讨论】:

  • 此外,如果您使用的是不支持 f 字符串的旧版 python,您可以将最后一行替换为:print('IP: {}, Port: {}'.format(ipx, portx))
  • 非常感谢。正是我想要的。
【解决方案2】:

如果你的服务器的响应是一个字符串,那么你可以这样做:

inList = '127.0.0.1,45403;127.0.0.1,47146;127.0.0.1,52888'
inList = [[elem for elem in item.split(',')] for item in inList.split(';')]

for ip, port in inList:
  print(ip)
  print(port)

输出:

127.0.0.1
45403
127.0.0.1
47146
127.0.0.1
52888

【讨论】:

    【解决方案3】:

    您可以创建一个 OrderedDict 并将所有 ips 和端口保存在一个列表中

    from collections import OrderedDict
    d=OrderedDict()
    
    d.setdefault('ip',[])
    d.setdefault('port',[])
    
    inList = '127.0.0.1,45403;127.0.0.1,47146;127.0.0.1,52888'
    for i in inList.split(';'):
        temp=i.split(',')
        d['ip'].append(temp[0])
        d['port'].append(temp[1])
    print(d)
    

    输出

    OrderedDict([('ip', ['127.0.0.1', '127.0.0.1', '127.0.0.1']),
                 ('port', ['45403', '47146', '52888'])])
    

    【讨论】:

      【解决方案4】:

      好的,你已经完成了一半,你需要的是:

      ipx = lista.split(";")[0].split(“,”)[0]
      portx = lista.split(";")[0].split(“,”)[1]
      print ipx
      print portx
      

      如果你想注册多个 IP 地址,我会使用字典:

      Ip_port = dict()
      For i in all-data:
            a = i.split(";")[0].split(“,”)[0]
           Ip_port[a] = i.split(";")[0].split(“,”)[1]
      

      想象你在一个 python 列表中拥有你所有的“列表”。

      【讨论】:

        猜你喜欢
        • 2018-01-10
        • 2021-04-22
        • 2015-04-27
        • 2023-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-12
        • 2019-01-09
        相关资源
        最近更新 更多