sam
sam

Reputation: 19164

tuple digits to number conversion

I am working on python and I'm stuck on this issue.

Input (there is a tuple):

a = (0, 1)

Output:

a = 0.1

Upvotes: 4

Views: 2017

Answers (2)

jamylak
jamylak

Reputation: 133574

Single digits and only two elements

>>> a = (0, 1)
>>> a[0] + a[1] * 0.1
0.1

Multiple single digits

>>> from itertools import count
>>> a = (0, 1)
>>> sum(n * 10 ** i for i, n in zip(count(0, -1), a))
0.1
>>> a = (0, 1, 5, 3, 2)
>>> sum(n * 10 ** i for i, n in zip(count(0, -1), a))
0.15320000000000003   

Using reduce (for Py 3.0+ you will need: from functools import reduce)

>>> a = (0, 1, 5, 3, 2)
>>> reduce(lambda acc, x: acc * 0.1 + x, reversed(a))
0.1532

Using the decimal module

>>> from decimal import Decimal
>>> a = (0, 1, 5, 3, 2)
>>> Decimal((0, a, -len(a) + 1))
Decimal('0.1532')

Any two numbers

>>> a = (0, 1)
>>> float('{0}.{1}'.format(*a))
0.1

Any numbers

>>> a = (0, 1, 5, 3, 2)
>>> float('{0}.{1}'.format(a[0], ''.join(str(n) for n in a[1:])))
0.1532

There may be some floating point inaccuracies, which you could fix by using Decimals eg.

>>> sum(Decimal(n) * Decimal(10) ** Decimal(i) for i, n in zip(count(0, -1), a))
Decimal('0.1532')

Upvotes: 10

fraxel
fraxel

Reputation: 35269

Assuming the elements of your list a are single digit 0-9, you can use maths:

>>> a[0] + a[1] * 0.1
0.10000000000000001

or convert to strings, concatenate and convert back to float:

>>> float(str(a[0])+'.'+str(a[1]))
0.10000000000000001

Upvotes: 1

Related Questions