-2

I have a tuple of fractions:

data = (-17/7, 5/14, -11/14)

I want an additional tuple with their decimal equivalents:

(-2.43, 0.36, -0.79)

This will work:

print((round(float(data[0]),2),  


round(float(data[1]),2),


round(float(data[2]),2)))

but I would like something more concise. I tried this list comprehension (which I can turn into a tuple later):

data1 = [round(float(data[i]),2) for i in data]

but got this error message: tuple indices must be integers or slices, not Rational

Tried many Python searches but no one seems to address this problem.

pppery
  • 3,731
  • 22
  • 33
  • 46

1 Answers1

1

Looking at the error you got, it points to where you're using indices:

data1 = [round(float(data[i]),2) for i in data]

The problem is in data[i], since you're using i as an index.

As the error states, i is not an integer.

Here, you really want i

To get the results you want, you can edit your code to this:

data1 = (* [round(float(i), 2) for i in data], )

Note: The * is used to unpack the items out of the list

Jorge Gx
  • 311
  • 3
  • 13