繁体   English   中英

数组迭代如何使用“and”?

[英]How does array iteration work with "and"?

如果索引有效,我想一次通过索引 +/-1 处的数组迭代三个项目。 我遇到了这个解决方案:

例子:

A = [0, 1, 2, 3, 4]
for i in range(len(A)):
   print(A[i and i-1:i+2])

#[0, 1]
#[0, 1, 2]
#[1, 2, 3]
#[2, 3, 4]
#[3, 4]

A[i and i-1:i+2]工作? 我不确定A[0 and -1:2]如何在数组中工作。

我查看了 Python 文档并说“表达式 x 和 y 首先计算 x;如果 x 为假,则返回其值;否则,计算 y 并返回结果值。” https://docs.python.org/3/reference/expressions.html#and

但是,这似乎与数组拼接不同。

也许查看切片边界的输出会有所帮助(为了清楚起见,我在下限周围添加了括号

A = [0, 1, 2, 3, 4]
for i in range(len(A)):
   print((i and i-1), i+2, A[(i and i-1):i+2])

这打印(我的评论):

0 2 [0, 1]    # lower bound => (0 and -1); 0 is falsy, so 0
0 3 [0, 1, 2] # lower bound => (1 and 0); 1 is true, so 0, based on your link
1 4 [1, 2, 3] # lower bound => (2 and 1); 2 is true, so 1, based on your link
2 5 [2, 3, 4] # ...
3 6 [3, 4]    # Degenerate slice indices (6) are handled gracefully

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM