Loop through python list of tuples and change the 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 Rob's last name to Roberto if id = 2
So my idea was to change a tuple to a list so that it would be easy to make a 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 it didn’t work, you guys don’t know how to do it?

Thanks!

+4
source share
5 answers

It does:

 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 

Print

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

If you want to understand the list, this is:

 >>> [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')] 
+4
source

Try the following:

 for idx, row in enumerate(a): id, name, surname, valA, valB = row if id == 2 and surname == 'Rob': a[idx] = (id, name, 'Roberto', valA, valB) 
+2
source

short answer

 a_list = [(_id, first, 'Roberto' if (last == 'Rob' and _id == 2) else last, x,y) for _id, first, last, x, y in a ] 

This is an understanding of the python list, which is a great tool for python.

The above values ​​have the same meaning as the following code:

 a_list = [] for _id, first, last, x, y in a: if last == 'Rob' and _id == 2: last =' Roberto' a_list.append((_id, first, last, x, y)) 
+2
source

Try the following:

 a=[(1,'Rach', 'Mell', '5.11', '160'),(2, 'steve', 'Rob', '6.1', '200'), (1,'Rach', 'Mell', '5.11', '160')] a_list = [] for ele in a: a_list.append(list(ele)) for ele in a_list: if ele[0] == 2: ele[2] = "Roberto" print a_list 
+2
source

I'm not very familiar with Python, but here

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

You do not select an item from your list. Try

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

X selects a tuple in the list, and parentheses select the data inside the tuple.

+1
source

All Articles