0
我不認爲我的長代碼對於這個問題是必要的,但是我有一個程序,它給了我輸入的所有數字,輸入的所有正數以及輸入的所有非正數的平均值。Python在字典內打印3個值
# Receive number inputs from user, turning it into a list.
def getInput():
numList = []
while True:
z = float(input("Enter a number (-9999 to quit): "))
if z == -9999:
return numList
else:
numList.append(z)
numList = getInput()
# Splitting the whole list of numbers into positive list, and non positive list.
def splitPosNonPos():
posList=[]
nonPosList=[]
for z in numList:
if z > 0:
posList.append(z)
else:
nonPosList.append(z)
return (posList, nonPosList)
posList, nonPosList = splitPosNonPos()
print()
print("All numbers ", numList)
print("Positive numbers ", posList)
print("Non positive numbers ", nonPosList)
# finding the average of all numbers
def computeAllAvg():
average = 0
sum = 0
for n in numList:
sum = sum + n
average = sum/len(numList)
return average
allNumAvg = computeAllAvg()
# finding the average of positive numbers
def computePosAvg():
average = 0
sum = 0
for n in posList:
sum = sum + n
average = sum/len(posList)
return average
posNumAvg = computePosAvg()
# finding average of non positive numbers
def computeNonPosAvg():
average = 0
sum = 0
for n in nonPosList:
sum = sum + n
average = sum/len(nonPosList)
return average
nonPosNumAvg = computeNonPosAvg()
print("All num average ", allNumAvg)
print("Pos num average ", posNumAvg)
print("Non Pos num average ", nonPosNumAvg)
我的價值觀allNumAvg,posNumAvg和nonPosNumAvg都返回我彩車,我可以輕鬆地打印,但這不是目前我多麼想打印出來。我需要能夠在字典中顯示它們,以便實際輸出看起來像這樣 -
{'AvgPositive':(正浮點數),'AvgNonPos':(浮點數非正數),'AvgAllNum' :(所有數字浮動)}
是否有某種功能,我可以採取我的三個值,將它們分配給這三個鍵,並像這樣呈現它們?
謝謝!
謝謝,實際上我只是在等待答案,哈哈。是的,它看起來並不是最實用的方法,但這是我被要求做的。 – user3344446