[英]Does append() function add both index and value to another list?
Heres the code I'm trying to understand:这是我试图理解的代码:
The code is the implementation of Sieve of Erastothenes.代码是 Erastothenes 筛法的实现。 If I understand it correctly, then up to line 8, the code creates a list of prime numbers up to N and the list is a boolean list where True - prime;
如果我理解正确,那么直到第 8 行,代码会创建一个最多为 N 的素数列表,该列表是 boolean 列表,其中 True - prime; False - non-prime;
False - 非素数; and the index number matches with the number we output.
并且索引号与我们output的编号匹配。
My question is: For lines 9-13 does the script "rewrite" the primes (which are just True values) with both the index and the boolean value in a new list in order for us to print them at the end?我的问题是:对于第 9-13 行,脚本是否使用新列表中的索引和 boolean 值“重写”素数(它们只是 True 值),以便我们在最后打印它们? Also, if primes is a boolean list, why python prints the index values at the end instead of just a bunch of True arguments?
此外,如果素数是 boolean 列表,为什么 python 会在末尾打印索引值而不是一堆 True arguments?
Update: I got it, thanks guys, range is a set of integers from 2 - n+1, hence i is integer as well.更新:我明白了,谢谢大家,范围是一组从 2 到 n+1 的整数,因此 i 也是 integer。 thats why I get integers in the primes string.
这就是为什么我在素数字符串中得到整数。 For some reason I was thinking of range as list1 initialy
出于某种原因,我最初认为 range 是 list1
def sita(N):
list1 = [True for _ in range(N + 1)]
list1[0:1] = [False, False]
for start in range(2, N + 1):
if list1[start]:
for i in range(2 * start, N + 1, start):
list1[i] = False
primes = [] #create empty list
for i in range(2, N + 1):
if list1[i]:
primes.append(i)
return primes
print(sita(int(input("Dati un numar N: "))))
primes.append(i)
only appends its argument, i
. primes.append(i)
仅附加其参数i
。 There is no magic that would additionally append anything else to the list.没有魔法可以将 append 其他任何东西添加到列表中。
In your code, there are two separate, independent lists: list1
and primes
:在您的代码中,有两个独立的列表:
list1
和primes
:
The first contains a boolean for each non-negative integer.第一个包含一个 boolean 用于每个非负 integer。
The second contains those integers for which list1
contained True
at the end of the first loop (this is what the if list1[i]
check does).第二个包含那些在第一个循环结束时
list1
包含True
的整数(这就是if list1[i]
检查所做的)。
Your loop, for i in range(2, N + 1):
is looping over the actual indices.您的循环
for i in range(2, N + 1):
正在遍历实际索引。 It tests the boolean value in list1[i]
, but only stores the index.它测试
list1[i]
中的 boolean 值,但只存储索引。 The boolean value ( list1[i]
) need not be written; boolean 值 (
list1[i]
) 无需写入; the mere fact that you append
ed i
indicates that the test passed, and i
is known to correspond to a prime number.您
append
编辑i
的事实表明测试通过,并且已知i
对应于素数。 Since primes
is built from scratch, it contains no booleans at all, just the various i
values (tested and found prime) append
ed to it in the final loop.由于
primes
是从头开始构建的,因此它根本不包含布尔值,只有各种i
值(经过测试并找到素数) append
在最终循环中对其进行了编辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.