Skip to main content
 首页 » 编程设计

python之使用python中的循环访问列表中的索引

2024年10月01日15fff_TT

我想弄清楚如何解决这个问题。我知道答案,但我不明白为什么它是正确的。

primes = [2, 3, 5, 7, 11] 

执行下面的循环后,它包含什么?

for i in range(2): 
     primes[4 - i] = primes[i] 

answer: 2, 3, 5, 3, 2

我被困在 primes[4 - i]... 部分。有人可以解释这部分吗?我知道是索引位置。

请您参考如下方法:

range(n) 为您提供从 0 到 n - 1 的数字序列。

如果您用代码中的顺序替换 range 函数,您基本上会得到:

for i in [0, 1]: 
     primes[4 - i] = primes[i] 

每次循环,i都会从0开始,越来越大。 这反过来意味着 4 - i 将从 4 开始变小。

1st loop: 4 -i = 4 - 0 = 4

2nd loop: 4 - i = 4 - 1 = 3

(and so on if your value in range was bigger than 2)

行 primes[4 - i] = primes[i] 意味着您要将索引 4 - i 中存储的值分配给索引 我。

在您的示例中,您的循环实际上是这样做的:

1st loop: primes[4] = primes[0]

2nd loop: primes[3] = primes[1]

为您提供当前的结果。