用 python 将列表中的一个字符串值分成两个值

separation one string value into two value in list with python

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

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

所需的输出是:

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

也就是说我要把TCP和UDP的大写字母换成小写字母,还要把UDP/TCP分成两个列表。 (我的问题是如何为分离编写代码)

我的代码是:

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)
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)

类似下面的东西

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']]

如果要更新同一个列表,

>>> 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']]