簡體   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