[英]Python Printing 3 values inside a dictionary
I don't think my long code is necessary for this question, but I have a program that gives me the average of all numbers entered, all positive numbers entered, and all non positive numbers entered. 我认为我的长代码对这个问题不是必需的,但是我有一个程序可以为我提供所有输入数字,所有输入正数字和所有非正数字的平均值。
# 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)
My values allNumAvg, posNumAvg, and nonPosNumAvg all return me floats which I can easily print, but this isn't currently how I want to print them. 我的值allNumAvg,posNumAvg和nonPosNumAvg都返回了我可以轻松打印的浮点数,但是目前这不是我要打印它们的方式。 I need to be able to present them in a dictionary, so that the actual output looks like this-
我需要能够在字典中显示它们,以便实际输出看起来像这样-
{'AvgPositive': (The positive float), 'AvgNonPos': (non positive number float), 'AvgAllNum': (all number float)} {'AvgPositive':(正浮点数,'AvgNonPos':(非正数浮点数),'AvgAllNum':(全数浮点数)}
Is there some sort of function where I can take my three values, assign them to those three keys and present them like that? 是否有某种函数可以让我取三个值,将它们分配给这三个键并像这样显示它们?
Thank you! 谢谢!
print({'AvgPositive': posNumAvg,
'AvgNonPos': nonPosNumAvg,
'AvgAllNum': allNumAvg})
I don't know why you'd want to print your output in a dict, though. 不过,我不知道为什么要在字典中打印输出。 You're not going to be able to control what order the key-value pairs occur in, and it's not the most readable of formats.
您将无法控制键值对的出现顺序,并且不是最易读的格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.