所以這是我的代碼。我目前正在學習Udacity課程,為他們的一個測驗編了這段代碼。它給出了我想要的答案......但可能出現了太多的迭代,我不太確定原因。如果有人能幫助我把它減少到一個迭代或列印的回應,那就太好了。
numList = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23,
86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
oddNumList = []
總數 = 0 ]
for num in numList:
if num % 2 != 0:
oddNumList.append(num)
if len(oddNumList) < 5:
print("在這個串列中有超過5個奇數")
else:
for ele in range(0, len(oddNumList))。
total = total oddNumList[ele]
print("所有奇數的總和是{}!".format(total))
uj5u.com熱心網友回復:
你做了很多思考,不止一個。如果我必須猜測,我會嘗試:
numList = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23,
86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
oddNumList = []
總數 = 0 ]
for num in numList:
if num % 2 != 0:
oddNumList.append(num)
# output part: oddNumList.
if len(oddNumList) < 5:
print("在這個串列中有超過5個奇數")
else:
for ele in range(0, len(oddNumList))。
total = total oddNumList[ele]
print("所有奇數的總和是{}!".format(total))
否則,每次檢查后都會呼叫輸出函式。
還可以嘗試用sum函式來計算總數。sum(oddNumList)
uj5u.com熱心網友回復:
你不需要對串列進行兩次迭代,在一次運行中完成對奇數的過濾和對其總和的計算就足夠了。另外,我把列印資訊的作業移出了回圈,所以它只在計算完成后才列印。
numList = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23,
86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
oddNumList = []
總數 = 0 ]
for num in numList:
if num % 2 != 0:
oddNumList.append(num)
# Add odd number to total: oddNumList.append(num)
total = total num
# 列印奇數串列的長度資訊 # 列印奇數串列的長度資訊if len(oddNumList) < 5:
print("在這個串列中有超過5個奇數")
# 列印所有奇數的總數。
print("Sum of all odd numbers is {}!".format(total)
uj5u.com熱心網友回復:
oddNumList = [x for x in numList if x%2! =0]
print("這個串列中有5個以上的奇數") if len(oddNumList)> 5 else print("less then 5"/span>)
for n in oddNumList:
總數=總數 n
print("Sum of all odd numbers is {}!".format(total))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/307313.html
標籤:
