I would like to convert a decimal value to a float value. Thank you in advance for a solution.
This is how my list looks like:
data = [('CUS002', 'ARTNUM423', 'Product 1234', Decimal('12.75'), 10), ('CUS005', 'ARTNUM784', 'Product 54628', Decimal('24.95'), 9)]
Should the result look like:
data = [('CUS002', 'ARTNUM423', 'Product 1234', 12.75, 10), ('CUS005', 'ARTNUM784', 'Product 54628', 24.95, 9)]
My attempt to solve it with this
data = [float(x[3]) for x in data]
does not quite work. I'm sure the solution is simple, but I'm completely blocked right now.
CodePudding user response:
Create a new list of tuples using comprehension:
>>> [tuple(x if i!=3 else float(x) for i, x in enumerate(t)) for t in data]
[('CUS002', 'ARTNUM423', 'Product 1234', 12.75, 10),
('CUS005', 'ARTNUM784', 'Product 54628', 24.95, 9)]
CodePudding user response:
Tuples are immutable, so in order to work, new tuples need to be created:
from decimal import Decimal
data = [('CUS002', 'ARTNUM423', 'Product 1234', Decimal('12.75'), 10),
('CUS005', 'ARTNUM784', 'Product 54628', Decimal('24.95'), 9)]
result = [(a, b, c, float(d), e) for a, b, c, d, e in data]
print(result)
Alternative shorter version, using extended iterable unpacking:
result = [(*head, float(d), e) for *head, d, e in data]