Reputation: 427
Hi i am stuck on change value in tuple type. i know i cant change value in tuple type but is there a way to change it ???
a=[('z',1),('x',2),('r',4)]
for i in range(len(a)):
a[i][1]=(a[i][1])/7 # i wanna do something like this !!!
i wanna change the the number in a to be the probability eg:1/7, 2/7, 4/7 and is there a way to change the number of a to be a float ?? eg
a=[('z',0.143),('x',0.285),('r',0.571)]
Upvotes: 2
Views: 6612
Reputation: 133554
To change to float
it's easy to just do
from __future__ import division # unnecessary on Py 3
One option:
>>> a=[('z',1),('x',2),('r',4)]
>>> a = [list(t) for t in a]
>>> for i in range(len(a)):
a[i][1]=(a[i][1])/7
>>> a
[['z', 0.14285714285714285], ['x', 0.2857142857142857], ['r', 0.5714285714285714]]
Probably the best way:
>>> a=[('z',1),('x',2),('r',4)]
>>> a[:] = [(x, y/7) for x, y in a]
>>> a
[('z', 0.14285714285714285), ('x', 0.2857142857142857), ('r', 0.5714285714285714)]
As requested in the comments, to 3 decimal places for "storing and not printing"
>>> import decimal
>>> decimal.getcontext().prec = 3
>>> [(x, decimal.Decimal(y) / 7) for x, y in a]
[('z', Decimal('0.143')), ('x', Decimal('0.286')), ('r', Decimal('0.571'))]
Upvotes: 2
Reputation: 500357
The easiest is perhaps to turn the tuples into lists:
a=[['z',1], ['x',2], ['r',4]]
Unlike tuples, lists are mutable, so you'll be able to change individual elements.
Upvotes: 4