简体   繁体   中英

Convert every nth element in a list

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.

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM