簡體   English   中英

任何人都可以幫我解決這個列表的 python 代碼,但我認為它沒有工作

[英]Can anyone help me with my python code for this list, not working how I think it should

所以我的編碼知識非常非常有限,我在這里使用的代碼有一半是我今天學到的,但我試圖做的是創建一個長度為 2020 正整數的列表,其中排除了所有可被 3 或 4 整除的數字但不是 5。我試圖弄清楚 2020 年的數字是多少,但我注意到在我的最終列表中排除了數字,它仍然在最后!

這是我寫的代碼:

numbers = [*range(1, 2165, 1)]
#print(numbers)

list1 = [ x for x in range(1, 2165) if x % 3 == 0 and x % 4 == 0 and x % 5 != 0 ]
#print(list1)

for x in list1:
    numbers.remove(x)
print(len(numbers))
print(numbers)

就像我說的我不太擅長編碼,但它似乎確實在列表的早期工作,因為排除了 12 個,剩下 60 個,但到最后,剩下 2139 個,可以被 3 整除。我會很感激任何幫助。

2020 正整數長

對於這樣的事情,與其在固定范圍內迭代(在您的情況下,從 1 到 2165,這不會產生符合您條件的 2020 年數字),不如構建一個為您提供所需數字的生成器通常更簡單,並通過next()從中獲取數字,直到您擁有所需數量為止。 在這種情況下,鑒於您的條件

def my_generator():
  x = 0
  while True:
    x += 1
    # skip all numbers that are divisible by (3 or 4) but are not divisible by 5
    if ((x % 3 == 0) or (x % 4 == 0)) and (x % 5) != 0:
      continue
    yield x

# initialize the generator, and then grab exactly 2020 numbers from it
gen = my_generator()
numbers = [next(gen) for _ in range(2020)]
print("The 2020th number meeting the conditions is", numbers[-1])
# 3367

請注意,在您最初的問題中,您的if條件編碼不正確,我已在此處修復它。

如果您只是通過顯式聲明您嘗試匹配的條件而不是在多個步驟中執行它來直接構建列表,它可能會簡化您的調試。 您可以在單個理解中生成numbers

[x for x in range(1, 2165) if not(x % 3 == 0 and x % 4 == 0 and x % 5 != 0)]

或邏輯等價物:

[x for x in range(1, 2165) if x % 3 != 0 or x % 4 != 0 or x % 5 == 0]

如果您不相信這是相同的,您可以根據原始代碼生成的numbers列表對其進行測試:

>>> numbers == [x for x in range(1, 2165) if not(x % 3 == 0 and x % 4 == 0 and x % 5 != 0)]
True

2139 出現在此列表中,因為2139 % 4 != 0

如果這與您嘗試捕獲的條件不匹配,簡化代碼應該更容易找到和解決問題。

暫無
暫無

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

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