我創建了一個代碼,它從用戶那里獲取一個串列,然后要求用戶選擇只列印奇數還是偶數。但是每當用戶選擇時,執行就會凍結。使用鍵盤中斷,我發現執行在奇數或偶數函式中停止。請幫忙 !!!
這是代碼:
from os import lstat
def odd(lst,oddlst):
for i in range(0,n):
while(lst[i]%2!=0):
oddlst.append(lst[i])
return oddlst
def even(lst,evenlst):
for i in range (0,n):
while(lst[i]%2==0):
evenlst.append(lst[i])
return evenlst
lst = []
oddlst = []
evenlst = []
n = int(input("enter number of elements \n"))
print("\nenter the elements \n")
for i in range(0,n):
num = int(input())
lst.append(num)
print(lst)
choice = input(" Do you want to print odd elements or even elements \n (odd/even)
\n")
if(choice=="odd"):
odd(lst,oddlst)
print(oddlst)
elif(choice=="even"):
even(lst,evenlst)
print(evenlst)
else:
print("invalid choice")
uj5u.com熱心網友回復:
也許您打算在and函式中使用 anif而不是 a 。whileoddeven
您的執行“凍結”的原因是您遇到了無限回圈。在任何時候,第i-th 元素都會被檢查,然后附加到一個串列中。但是,您要檢查的條件不會改變, index 也不會改變i。
將您的 s 更改while為ifs 應該可以解決您的問題。
此外,為了更優雅地解決您的問題,請查看:
https ://docs.python.org/3/library/functions.html#filter
How to filter a list
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515915.html
標籤:Python列表功能附加
上一篇:添加到嵌套串列
