Transform all elements of a list into floats

Asked

Viewed 6,005 times

1

That’s the code I wrote.

n_alunos=input('')
x=0
idades=[]
alturas=[]

while x != n_alunos:
    x+=1
    n=raw_input('')
    a=n.split(" ")
    idades.append(a[0])
    alturas.append(a[1])

How to transform the elements of the 2 string lists to float ?

1 answer

5

To convert an existing list of strings into a list of floats:

lista = [float(i) for i in lista]

Source: https://stackoverflow.com/questions/1614236/in-python-how-do-i-convert-all-of-the-items-in-a-list-to-floats

The tbm conversion can be performed directly in the append:

idades.append(float(a[0]))

I rewrote your code to python3 by performing the conversion like this (and some other modifications). If you prefer:

#!/usr/bin/python3
n_alunos = int(input('N. de alunos:    '))
idades = []
alturas = []
for i in range(n_alunos):
    dados = input('Idade/altura:    ').split(" ")
    idades.append(float(dados[0]))
    alturas.append(float(dados[1]))
  • 1

    map(float, list) is also a good

Browser other questions tagged

You are not signed in. Login or sign up in order to post.