[英]Getting values from all the indices of a list (Determining Prime Numbers)
首先,我是Python的新手。 我正在嘗試通過模運算%
來確定數字(例如167)是否是質數。
例如,讓167 % n = some value i
當167 % 1
和167 % 167
,它應該返回0,並且對於range(2,166)
在range(2,166)
n,它應該給出167 % n
的余數。 我的問題是,當n = 1 ~ 167
167 % n
時,我試圖打印余數,但不知道如何獲取列表索引的值(應該是余數)。
所以,這就是我所擁有的:
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.
如果可以使用while循環,那就更好了,那應該更加清楚。 因此,雖然i
從1-167進行了迭代,但它應該將結果x
添加到列表的索引中,並且我想打印這些結果。
有什么推薦的人嗎? 任何幫助表示贊賞! 謝謝你
這將創建所有不等於零的余數的列表:
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
您的代碼中存在許多問題:
i = 0
是沒有意義的,因為在循環之前沒有使用i = 0
,而是在循環中對其進行了覆蓋。 167 % i == x
將余數與不存在的x
進行比較。 你想結果分配給x
與x = 167 % i
。 L[i].append(x)
在索引i
處附加L
的元素,但您想通過L.append(x)
將x
附加到L
print(L[x])
但你需要使用print(L[i])
更簡單,只打印remainder
與print(remainder)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.