[float(i) for i in lst]
prorgamming newbie--I was looking for answers to an exercise I was doing and got my answers from 开发者_如何学Pythonhere. My question is this--from that thread, the one chosen as best answer, was this code
[float(i) for i in lst]
The code did what it was supposed to do, but when I tried to get to that new list, I am getting errors
>>> xs = '12 10 32 3 66 17 42 99 20'.split()
>>> [float(i) for i in xs]
[12.0, 10.0, 32.0, 3.0, 66.0, 17.0, 42.0, 99.0, 20.0]
>>> i
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
How should I do it?
Thanks!
You have to assign [float(i) for i in xs]
to something:
>>> new_list = [float(i) for i in xs]
>>> new_list
[12.0, 10.0, 32.0, 3.0, 66.0, 17.0, 42.0, 99.0, 20.0]
>>> new_list[0]
12.0
>>> new_list[5]
17.0
Using map:
xs = '12 10 32 3 66 17 42 99 20'.split()
new_xs = map(float, xs)
Unlike for loops that leave the last iteration bound to the variable the var inside a list comp stops existing after evaluation.
i
only exists inside the list comprehension.
You want to say:
i = [float(i) for i in lst]
This is something related to Python versions. Look: On Python 2, if you do:
>>> i = 1234
>>> j = [i for i in xrange(10)]
>>> print i
9
But this was fixed in Python 3:
>>> i = 1234
>>> j = [i for i in range(10)]
>>> print(i)
1234
If you have Python 3.0 or superior, the variable will only be available in the comprehension. It will not affect the rest of the environment
As an alternative to assigning a name to your list comprehension, in Python interactive mode, the symbol _
is automatically assigned to the last expression evaluated by the interpreter. So you could do the following:
>>> xs = '12 10 32 3 66 17 42 99 20'.split()
>>> [float(i) for i in xs]
[12.0, 10.0, 32.0, 3.0, 66.0, 17.0, 42.0, 99.0, 20.0]
>>> _
[12.0, 10.0, 32.0, 3.0, 66.0, 17.0, 42.0, 99.0, 20.0]
>>> _[2]
32.0
>>> _
32.0
精彩评论