簡體   English   中英

從列表的所有索引中獲取值(確定質數)

[英]Getting values from all the indices of a list (Determining Prime Numbers)

首先,我是Python的新手。 我正在嘗試通過模運算%來確定數字(例如167)是否是質數。

例如,讓167 % n = some value i

167 % 1167 % 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進行比較。 你想結果分配給xx = 167 % i
  • 您嘗試使用L[i].append(x)在索引i處附加L的元素,但您想通過L.append(x)x附加到L
  • 最后,你試圖讓你只使用增值print(L[x])但你需要使用print(L[i])更簡單,只打印remainderprint(remainder)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM