[英]Conditional Statement Python3
I'm wondering what the following is evaluating to on each iteration, I've checked the internet but can't find any definite answers 我想知道以下内容在每次迭代中的效果如何,我已经检查了互联网,但找不到明确的答案
And also if there's anymore efficient ways to do it. 还有是否还有其他更有效的方法可以做到这一点。
for i in range(0, len(c)):
if i & True:
pass
True
has an integer value of 1
in Python, so when the loop iterates an integer i
from 0
to the length of c
and performs bitwise-and on i
and 1
, it effectively checks if i
is an odd number and if so, executes the pass
statement (where I believe there are more code in your real code). True
在Python中的整数值为1
,因此当循环从0
到c
的长度迭代整数i
并按位执行时,对i
和1
有效检查i
是否为奇数,如果是,则执行pass
语句(我相信您的实际代码中还有更多代码)。
As for a more efficient way to do it, instead of generating all the numbers between 0 and the length of c
and filtering out even numbers, you can use the step
parameter of the range
function to generate the desired sequence of odd numbers in the first place: 作为一种更有效的方法,您可以使用
range
函数的step
参数在第一个函数中生成所需的奇数序列,而不是生成介于0和c
的长度之间的所有数字并过滤掉偶数,而不是生成所有数字。地点:
for i in range(1, len(c), 2):
pass
i & True
evaluates to 0
for even numbers and 1
for odd numbers. i & True
对偶数求值为0
,对奇数求0
1
。
for i in range(0, 5):
print(i, i & True)
yields: 收益率:
(0, 0)
(1, 1)
(2, 0)
(3, 1)
(4, 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.