Luca Lazzati
Luca Lazzati

Reputation: 65

Changing values on a list of lists

I wish could change this list of lists with other values:

DD = [['10.0.11.100', '10.0.11.10', '10.0.12.10', '10.0.12.100'],
      ['10.0.11.100', '10.0.11.10', '10.0.1.6', '10.0.13.10', '10.0.13.100'],
      ['10.0.11.100','10.0.11.10','10.0.1.6','10.0.13.10','10.0.14.10','10.0.14.100'],
      ['10.0.11.100','10.0.11.10','10.0.1.6','10.0.1.14','10.0.4.6','10.0.22.10','10.0.22.100']]

And I would like to arrive at this result:

[['10.0.11.100', 'N1', 'N2', '10.0.12.100'],
['10.0.11.100', 'N1', '10.0.1.6', 'N3', '10.0.13.100'],
['10.0.11.100','N1','10.0.1.6','N3','N4','10.0.14.100'],
['10.0.11.100','N1','10.0.1.6','10.0.1.14','10.0.4.6','10.0.22.10','10.0.22.100']]

I tried to do this, but it's the wrong solution:

for v in DD:
    if v == '10.0.11.10':
      v[i] = 'N1'
    elif v == '10.0.12.10':
      v[i] = 'N2'
    elif v == '10.0.13.10':
      v[i] = 'N3'
    elif v == '10.0.14.10':
      v[i] = 'N4'
print(v)

['10.0.11.100',
 '10.0.11.10',
 '10.0.1.6',
 '10.0.1.14',
 '10.0.4.6',
 '10.0.22.10',
 '10.0.22.100']

This is my whole code:

DD = [['10.0.11.100', '10.0.11.10', '10.0.12.10', '10.0.12.100'],['10.0.11.100', '10.0.11.10', '10.0.1.6', '10.0.13.10', '10.0.13.100'],['10.0.11.100','10.0.11.10','10.0.1.6','10.0.13.10','10.0.14.10','10.0.14.100'],['10.0.11.100','10.0.11.10','10.0.1.6','10.0.1.14','10.0.4.6','10.0.22.10','10.0.22.100']]

for v in DD:
    if v == '10.0.11.10':
      v[i] = 'N1'
    elif v == '10.0.12.10':
      v[i] = 'N2'
    elif v == '10.0.13.10':
      v[i] = 'N3'
    elif v == '10.0.14.10':
      v[i] = 'N5'
print(v)

['10.0.11.100',
 '10.0.11.10',
 '10.0.1.6',
 '10.0.1.14',
 '10.0.4.6',
 '10.0.22.10',
 '10.0.22.100']

How could this be done?

Upvotes: 0

Views: 57

Answers (1)

William Goodwin
William Goodwin

Reputation: 464

You need to loop through the items in the nested lists. This should do it:

DD = [['10.0.11.100', '10.0.11.10', '10.0.12.10', '10.0.12.100'],
      ['10.0.11.100', '10.0.11.10', '10.0.1.6', '10.0.13.10', '10.0.13.100'],
      ['10.0.11.100','10.0.11.10','10.0.1.6','10.0.13.10','10.0.14.10','10.0.14.100'],
      ['10.0.11.100','10.0.11.10','10.0.1.6','10.0.1.14','10.0.4.6','10.0.22.10','10.0.22.100']] 

for v in DD:
    for i in range(len(v)):
        if v[i] == '10.0.11.10':
            v[i] = 'N1'
        elif v[i] == '10.0.12.10':
            v[i] = 'N2'
        elif v[i] == '10.0.13.10':
             v[i] = 'N3'
        elif v[i] == '10.0.14.10':
             v[i] = 'N4'

Upvotes: 2

Related Questions