[英][float(i) for i in lst]
prorgamming newbie--I was looking for answers to an exercise I was doing and got my answers from here . prorgamming新手 - 我正在寻找我正在做的练习的答案,并从这里得到我的答案。 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: 你必须为[float(i) for i in xs]
赋值:
>>> 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)
与将最后一次迭代绑定到变量的循环不同,列表中的var在评估后停止存在。
i
only exists inside the list comprehension. i
只存在于列表理解中。
You want to say: 你想说:
i = [float(i) for i in lst]
This is something related to Python versions. 这与Python版本有关。 Look: On Python 2, if you do: 看:在Python 2上,如果你这样做:
>>> i = 1234
>>> j = [i for i in xrange(10)]
>>> print i
9
But this was fixed in Python 3: 但这已在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. 如果您使用的是Python 3.0或更高版本,则该变量仅在理解中可用。 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. 作为为列表推导指定名称的替代方法,在Python交互模式中,符号_
自动分配给解释器评估的最后一个表达式。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.