2017-04-15 143 views
1

我想學習Python,但我對它仍然很陌生。我試圖創建一個數字列表,從2到用戶輸入的數字,然後通過列表並從列表中刪除所有非素數,然後再打印出來。我在計算時遇到了麻煩,因爲我不斷收到錯誤:列表索引超出範圍。我正在考慮使用for循環,但是然後變量i將低於變量current,並且我需要確保當它通過列表時我總是高於當前值。我只能使用基本功能和循環來完成任務。在Python中創建一個Primes列表並打印出列表3.6.1

counter = 2 

current = 2 

n = int(input("Please enter a number larger than 2. ")) 

while counter <= n: 
    userList.append(counter) 
    counter = counter + 1 

print("Printing out list ") 
print(userList) 

i = 1 

while i <= len(userList): 
    if userList[ i ] % current == 0: 
     userList.remove(userList[i]) 
     i = i + 1 
    else: 
     current = current + 1 

print(userList) 

回答

0

你的代碼有一些錯誤。

1)從大列表中刪除非常慢因爲您需要在刪除項目後移動所有項目以避免列表中的項目之間出現任何間隙。最好將項目標記爲已刪除,然後只需打印剩下的內容即可。

2)通過使用你的算法,你需要兩個while循環。

3)如果列表中有N項,則列表的最後一個索引是(N-1)。

更Python的解決方案:

#!/usr/bin/env python3 

n = int(input("Maximal number: ")) 
numbers = list(range(2, n+1)) 

i = 0 
while i < len(numbers): 
    if numbers[i] != None: 
     j = i + 1 
     while j < len(numbers): 
      if numbers[j] != None: 
       if numbers[j] % numbers[i] == 0: 
        numbers[j] = None 
      j += 1 
    i += 1 

print(list(filter(lambda x: x is not None, numbers)))` 
+0

我明白了。這個任務只允許我使用基本的循環和函數。不允許使用過濾器和lambda等關鍵字。我甚至不知道他們做了什麼。基本上,我只允許使用我在代碼中的內容,但這只是不正確的。 –

+0

基本上,您只需從未標記爲已刪除的值中創建新列表。您可以輕鬆地將其重寫爲循環和if語句。 – gcx11