Roh*_*ith -1 python for-loop python-2.7
我正在使用python 2.7.3当我尝试
a = [1,2,3,4]
b = []
for i in a:
b.append(1/i)
Run Code Online (Sandbox Code Playgroud)
我得到一个意想不到的输出,因为b = [1,0,0,0].但是,如果我打印i循环的值工作正常.
for i in a:
b.append(i)
Run Code Online (Sandbox Code Playgroud)
将给出b = [1,2,3,4]这是什么原因.我也是如何以正确的方式做同样的事情?
在python 2中,/当两个操作数都是整数时,表示整数除法.试试1.0 / i.
In [2]: 1 / 2
Out[2]: 0
In [3]: 1.0 / 2
Out[3]: 0.5
In [4]: 1 / 2.0
Out[4]: 0.5
Run Code Online (Sandbox Code Playgroud)
要使/操作符的行为与python 3中的操作符相同,请使用from __future__ import division:
In [11]: from __future__ import division
In [12]: 1 / 2
Out[12]: 0.5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
799 次 |
| 最近记录: |