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 ???
你好,我被卡在tuple类型的变更值上。我知道我不能改变tuple类型的值,但是有没有办法改变它???
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的值改为1/7,2/7,4/7,有办法改变a的数目吗?如
a=[('z',0.143),('x',0.285),('r',0.571)]
2 个解决方案
#1
2
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"
如在评论中所要求的,小数点后3位“存储而非打印”
>>> 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'))]
#2
4
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.
与元组不同,列表是可变的,因此您可以更改单个元素。
#1
2
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"
如在评论中所要求的,小数点后3位“存储而非打印”
>>> 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'))]
#2
4
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.
与元组不同,列表是可变的,因此您可以更改单个元素。