[英]Getting values from all the indices of a list (Determining Prime Numbers)
First and foremost I'm new to Python. 首先,我是Python的新手。 I am trying to determine if a number, let's say 167 is a prime number by using the modulo operation, %
. 我正在尝试通过模运算%
来确定数字(例如167)是否是质数。
Eg, Let 167 % n = some value i
例如,让167 % n = some value i
When 167 % 1
and 167 % 167
, it should return 0 and for n in range(2,166)
, it should be giving the remainder of 167 % n
. 当167 % 1
和167 % 167
,它应该返回0,并且对于range(2,166)
在range(2,166)
n,它应该给出167 % n
的余数。 The problem I have is that I am trying to print the remainder when 167 % n
for n = 1 ~ 167
but don't know how to get the values (which should be the remainder) of the indices of a list. 我的问题是,当n = 1 ~ 167
167 % n
时,我试图打印余数,但不知道如何获取列表索引的值(应该是余数)。
So, here's what I have: 所以,这就是我所拥有的:
L = [] #creates empty list
i=0 #initialize i?
for i in range(1, 168) :
if 167 % i == 0 :
print ("There is no remainder")
else :
167 % i == x # x should be the value of the remainder
L[i].append(x) #attempting to add x ... to the indices of a list.
print(L[x]) #print values of x.
It's even better if I can use the while loop, that should be much clearer. 如果可以使用while循环,那就更好了,那应该更加清楚。 So, while i
iterates from 1-167, it should be adding the results x
into the indices of the list and I want to print those results. 因此,虽然i
从1-167进行了迭代,但它应该将结果x
添加到列表的索引中,并且我想打印这些结果。
Any recommendation guys? 有什么推荐的人吗? Any help appreciated!! 任何帮助表示赞赏! Thanks a bunch. 谢谢你
This creates a list of all remainders that are not equal to zero: 这将创建所有不等于零的余数的列表:
L = []
for i in range(1, 168) :
remainder = 167 % i
if remainder == 0 :
print("There is no remainder")
else:
L.append(remainder)
print(remainder)
>>> len(L)
165
There are a number of problems in your code: 您的代码中存在许多问题:
i = 0
before the loop does not make sense because it is not used before the loop and overridden in the loop. 在循环之前设置i = 0
是没有意义的,因为在循环之前没有使用i = 0
,而是在循环中对其进行了覆盖。 167 % i == x
compares the remainder with a non-existing x
. 这是: 167 % i == x
将余数与不存在的x
进行比较。 You want to assign the result to x
with x = 167 % i
. 你想结果分配给x
与x = 167 % i
。 L
at index i
using L[i].append(x)
but you want to append x
to L
with L.append(x)
. 您尝试使用L[i].append(x)
在索引i
处附加L
的元素,但您想通过L.append(x)
将x
附加到L
print(L[x])
but you need to use print(L[i])
, simpler, just print remainder
with print(remainder)
. 最后,你试图让你只使用增值print(L[x])
但你需要使用print(L[i])
更简单,只打印remainder
与print(remainder)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.