![](/img/trans.png)
[英]How to change a list from saying true/false for even and odd numbers , to simply saying even or odd for each number?
[英]Why does cycle 'if' delete not all odd numbers from the list (only each second odd number)?
有一個代碼:
list = [1, 2]
while list[-1]+list[-2] <= 4000000:
list.append(list[-1] + list[-2])
for i in list:
if i % 2 == 1:
print(i)
list.remove(i)
print(list)
print(sum(list))
您不應該在迭代列表(或任何容器)時對其進行修改。
go 的一種方法是使用另一個容器,
in_list = [1, 2]
while in_list[-1]+in_list[-2] <= 20:
in_list.append(in_list[-1] + in_list[-2])
print(in_list)
out_list = []
for i in in_list:
if i % 2 != 1:
print(i)
out_list.append(i)
print(out_list)
print(sum(out_list))
此代碼使用與您不同的方法:它創建輸入列表,然后在迭代時將偶數元素添加到新的 output 列表中。 這與從輸入列表中刪除奇數元素具有相同的效果,但是,它不會通過修改輸入列表來中斷迭代。
就像評論中所說的那樣,您不應該使用內置名稱(“列表”)作為變量名稱 - 它會隱藏它們。 此外,當您開發和調試代碼時,最好堅持使用較小的示例。 在這里,我使用 20 而不是 4,000,000 - 更容易跟蹤並且不會失去意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.