Home > Net >  How to round values in a list containing tuples
How to round values in a list containing tuples

Time:05-23

I have a list, which has 2 more lists within it and both of the lists each have 2 tuples in them.

lst = [
  [('Jade', 0.9877607), ('Tom', 0.5728347)],
  [('Jackson', 0.6892309), ('Hazel', 0.6837777)]
]

I want to round all 4 float values to 2 d.p. Would I have to turn each tuple into a list and then change it or is there an easier way to do it?

Thanks!

CodePudding user response:

Since tuples are immutable, you cannot modify them in-place. You'll need to create a new list based on the current list.

This is very simple to do using a list comprehension:

lst = [
    [('Jade', 0.9877607), ('Tom', 0.5728347)], 
    [('Jackson', 0.6892309), ('Hazel', 0.6837777)],
]

new_list = [
    [(name, round(value, 2)) for (name, value) in sublist]  
    for sublist in lst
]
print(new_list)

# Output:

# [
#    [('Jade', 0.99), ('Tom', 0.57)],
#    [('Jackson', 0.69), ('Hazel', 0.68)]
# ]

CodePudding user response:

Tuples are immutable, which means if you want to "modify" them, you need to create whole new object. In your case it is easiest to create whole new list and reassign it to the original lst variable.

lst = [[(t[0], round(t[1], 2)) for t in lin] for lin in lst]

You could use the above list comprehension to create a new list.

CodePudding user response:

Since tuples are immutable, you would indeed need to turn each of the tuples into a list before modifying them. Another alternative, is to generate an amended version of each tuple with the numbers rounded to four decimal places.

If you are looking to just print the tuples with 2 decimal places, you can instead just use python f-strings:

num = lst[0][0][1]
print(f"{num:.2f}")

CodePudding user response:

for x in lst:
  print(round(x[0][1],2),round(x[1][1],2))

#output
0.99 0.57
0.69 0.68

Or if you want to create a new list:

k=[]
for x in lst:
  for y in x:
    k.append((y[0],round(y[1],2)))
  • Related