Home > Net >  How can I convert a list to float inside a for statement
How can I convert a list to float inside a for statement

Time:01-25

I have multiple lists of numerators and denominators that I'm counting as I parse through a site to get variables that I want to turn into fractions. (eg. a = [1, 2] should be converted to a = 0.5).

I've tried this:

a = [1, 2]
b = [3, 5]

for i in a, b:
  i = i[0]/i[1]
  print(i)

print(a, b)

and I get:

>>> 0.5
>>> 0.6
>>> [1, 2] [3, 5]

The variables return the output I'm looking for when printed inside the for statement but not outside. How can I fix this? For loop isn't necessary, if there's an easier way to do it I'm all ears.

(I'm using Python 3.10)

@Eli Harold:

>>> a = [1, 2]
>>> b = [1, 4]
>>> for i in a, b:
...     i = i[0]/i[1]
... 
>>> print(a)
[1, 2]
>>> print(b)
[1, 4]

CodePudding user response:

You can use a list comprehension:

c = [ n/d for n,d in [a,b] ] 

print(c)
[0.5, 0.6]
  • for ... in [a,b] will iterate through each list one by one
  • n,d will be unpacked from the first and second item of each list
  • [ n/d ... ] build a resulting list with each n and d provided by the for

you could assign the result to the original variables if needed:

a,b = ( n/d for n,d in [a,b] ) 

print(a,b)
0.5 0.6

CodePudding user response:

Try to use list comprehension. You will be able to store your results in a list and get them by list indexing. For example:
result = [x/y for x,y in zip(a,b)]

CodePudding user response:

You can save each result to a var like this:

for i, item in enumerate([i/j for i,j in [a,b]]):
    locals()["var"  str(i)] = item

However I would recommend using a dict instead:

d = {}
for i, item in enumerate([i/j for i,j in [a,b]]):
    d["var"  str(i)] = item
  •  Tags:  
  • Related