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)]
2
  • 1
    If you want change a tuple, you really need a list. Commented Apr 24, 2013 at 5:54
  • 2
    Replace the entire tuple, not just a component. Bam! Commented Apr 24, 2013 at 6:00

2 Answers 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.

Sign up to request clarification or add additional context in comments.

2 Comments

@TommyNgo: a = map(list, a).
@TommyNgo You have to make the items lists. a is already a list. Use map as seen above, or a list comprehension new_list = [list(x) for x in a].
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"

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

3 Comments

can the number somehow have 3 dp ??
for storing not for print it out
@TommyNgo floats don't work like that... you can however use the decimal module, I'll update to show that. Also why do you only want 3 places not for printing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.