1

I know that python is a crazy language because of it's cycles constructions :)

So, I have an array of numbers but in string type:

a = ['1', '40', '356', '...']

I need this or a copy of this array but with float type instead of string. The only thing is that the code should be in one line.

Help me, please :)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Max Frai
  • 61,946
  • 78
  • 197
  • 306

2 Answers2

11

You can use map()[docs] and float()[docs]:

b = map(float, a)
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
8
 a = ['1', '40', '356', '...']
 b = [float(x) for x in a]

This is called a list comprehension. It's a very powerful feature of Python, and you can read more about list comprehensions here:

http://docs.python.org/tutorial/datastructures.html#list-comprehensions

Steve Mayne
  • 22,285
  • 4
  • 49
  • 49