Python在字典中打印3个值

时间:2014-02-24 02:49:18

标签: python function dictionary

我不认为我的长代码对于这个问题是必要的,但是我有一个程序可以给我输入的所有数字的平均值,输入的所有正数以及输入的所有非正数。

# 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':(所有数字浮动)}

是否存在某种功能,我可以将三个值分配给这三个键并将它们呈现出来?

谢谢!

1 个答案:

答案 0 :(得分:1)

print({'AvgPositive': posNumAvg,
       'AvgNonPos': nonPosNumAvg,
       'AvgAllNum': allNumAvg})

我不知道你为什么要在dict中输出你的输出。您无法控制键值对出现的顺序,也不是最易读的格式。