2

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)]
4

2 回答 2

4

最简单的可能是将元组变成列表:

a=[['z',1], ['x',2], ['r',4]]

与元组不同,列表是可变的,因此您可以更改单个元素。

于 2013-04-24T05:52:48.837 回答
2

改变float它很容易做到

from __future__ import division # unnecessary on Py 3

一种选择:

>>> 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]]

可能是最好的方法:

>>> 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)]

根据评论中的要求, “存储和不打印”到小数点后 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'))]
于 2013-04-24T05:53:40.250 回答