【问题标题】:separation one string value into two value in list with python用python将一个字符串值分离为列表中的两个值
【发布时间】:2022-01-11 15:20:43
【问题描述】:

我有以下嵌套列表:(列表更长,但作为示例):

lst = [['IP 地址 1','TCP'], ['IP 地址 2','UDP'],['IP 地址 3','UDP/TCP']]

想要的输出是:

lst=[['IP地址1','tcp'],['IP地址2','udp'],['IP地址3','udp'],['IP地址3',' tcp']

这意味着我想用小写字母替换 TCP 和 UDP 的大写字母,并将 UDP/TCP 分成两个 list 。 (我的问题是如何为分离制作代码)

我的代码是:

lst = [['IP Address 1','TCP'], ['IP Address 2 ','UDP'],['IP Address 3','UDP/TCP']]
for x in lst:
    if x[1]=="TCP":
        x[1]="tcp"
    elif x[1]=="UDP":
        x[1] = "udp"
    elif x[1] == "UDP/TCP":
        x[1] = "udp" 
        x[1]="tcp"
print(lst)

【问题讨论】:

    标签: python list nested nested-lists


    【解决方案1】:
    lst = [['IP Address 1','TCP'], ['IP Address 2 ','UDP'],['IP Address 3','UDP/TCP']]
    for x in lst:
        if x[1]=="TCP":
            x[1]="tcp"
        elif x[1]=="UDP":
            x[1] = "udp"
        elif x[1] == "UDP/TCP":
            x[1] = "udp"
            lst.append([x[0], "tcp"])
    print(lst)
    

    【讨论】:

    • 非常感谢。它完美地工作
    【解决方案2】:

    类似下面的东西

    lst = [['IP Address 1','TCP'], ['IP Address 2 ','UDP'],['IP Address 3','UDP/TCP']]
    result = []
    for e in lst:
      if e[1] == 'UDP/TCP':
        result.append([e[0],'udp'])
        result.append([e[0],'tcp'])
      else:
        result.append([e[0],e[1].lower()])
    print(result)
    

    输出

    [['IP Address 1', 'tcp'], ['IP Address 2 ', 'udp'], ['IP Address 3', 'udp'], ['IP Address 3', 'tcp']]
    

    【讨论】:

    • 非常感谢。
    【解决方案3】:

    如果你想更新同一个列表,

    >>> lst = [['IP Address 1','TCP'], ['IP Address 2 ','UDP'],['IP Address 3','UDP/TCP']]
    >>> for i in lst:
    ...   i[1]=i[1].lower()
    ...   if '/' in i[1]:
    ...      lst.append([i[0], i[1].split('/')[0]])
    ...      lst.append([i[0], i[1].split('/')[1]])
    ...      lst.remove(i)
    ...
    >>> print(lst)
    

    输出:

       [['IP Address 1', 'tcp'], ['IP Address 2 ', 'udp'], ['IP Address 3', 'udp'], ['IP Address 3', 'tcp']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 2017-12-23
      • 2020-11-30
      相关资源
      最近更新 更多