简体   繁体   中英

Why tuple assignment failed?

I have tried to assign new data to existing tuple, and it does not work.and actually I want to add the a and b to get a sum, however only string can be iterated..

A=[('3', '4'), ('3', '11'), ('8', '10')] 
  print A
for a,b in A:
  a,b = int(a), int(b)+int(a)
print A

results:

[('3', '4'), ('3', '11'), ('8', '10')]

[('3', '4'), ('3', '11'), ('8', '10')]

When you set a, b = int(a), int(b)+int(a) , you do not change the actual object a and b came from; you just bind new objects the variables a and b...

You can create a new list B, and populate it:

A=[('3', '4'), ('3', '11'), ('8', '10')] 
print A
B = []
for a, b in A:
    B.append((int(a), int(b) + int(a)))
print B

You can use a list comprehension:

>>> [(int(i), int(i) + int(j)) for i, j in A]
[(3, 7), (3, 14), (8, 18)]

Tuples are immutable. Also, you're assigning new values to a,b in the for loop and doing nothing else with those new values.

http://docs.python.org/library/functions.html#tuple http://en.wikipedia.org/wiki/Immutable_object

Rather than creating a new list as per amit's answer you could use "enumerate" to get the index and write it back to your list which is, I think what you were trying to do.

enumerate() essentially returns a tuple of the current position in the iterable and then the value so you could do:

for idx, (a, b) in enumerate(A):
    A[idx] = (int(a), int(b) + int(a))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM