编程新手——我正在寻找我正在做的练习的答案,并从 here 得到了我的答案。 .我的问题是——在那个线程中,被选为最佳答案的是这段代码
[float(i) for i in lst]
代码做了它应该做的,但是当我试图访问那个新列表时,我遇到了错误
>>> 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
我应该怎么做?
谢谢!
最佳答案
您必须将 [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
关于python - [float(i) for i in lst],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6011759/