Home > database >  separation one string value into two value in list with python
separation one string value into two value in list with python

Time:12-07

I have the following nested list: (the list is more long but as example):

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

the desired output is :

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

that means I want to replace capital letters of TCP and UDP with small letters and also separate UDP/TCP into two list . (my problem is how make code for the separation)

my code is:

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)

CodePudding user response:

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)

CodePudding user response:

Something like the below

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)

output

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

CodePudding user response:

If you want to update the same list,

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

Output:

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