Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through a python list of tuples and change a value

I have this code

a=[(1,'Rach', 'Mell', '5.11', '160'),(2, 'steve', 'Rob', '6.1', '200'), (1,'Rach', 'Mell', '5.11', '160')]

I want to change the last name Rob to 'Roberto' if the id = 2
So my idea was to change the tuple to a list so it will be easy to make the change

I tried :

a_len = len(a)
count = 0
a_list = []
while(count < a_len):
     a_list.append(a[count])
     count ++

for x, element in a_list:
     if element[0] == 2:
          a_list[x] = Roberto

But this didn't work, do you guys have any idea how to do that?

Thanks!

like image 220
mongotop Avatar asked Dec 16 '22 13:12

mongotop


1 Answers

This does it:

a=[(1,'Rach', 'Mell', '5.11', '160'),(2, 'steve', 'Rob', '6.1', '200'), (1,'Rach', 'Mell', '5.11', '160')]

for i,e in enumerate(a):
    if e[0]==2: 
        temp=list(a[i])
        temp[2]='Roberto'
        a[i]=tuple(temp)

print a        

Prints:

[(1, 'Rach', 'Mell', '5.11', '160'), (2, 'steve', 'Roberto', '6.1', '200'), (1, 'Rach', 'Mell', '5.11', '160')]

If you want a list comprehension, this:

>>> [t if t[0]!=2 else (t[0],t[1],'Roberto',t[3],t[4]) for t in a]
[(1, 'Rach', 'Mell', '5.11', '160'), (2, 'steve', 'Roberto', '6.1', '200'), (1, 'Rach', 'Mell', '5.11', '160')]
like image 52
the wolf Avatar answered Dec 18 '22 03:12

the wolf