如何将用户输入的姓名和年龄列表分类为具有相应姓名的平均年龄,最高年龄和最低年龄?

时间:2019-04-26 02:24:21

标签: python list tuples

编写一个程序,提示用户输入一系列名称和年龄。 (使用假名称End标记值序列的结尾。)输入值后,打印平均年龄以及年龄最高和最低的那些人的姓氏和年龄。

我有将产生平均年龄,最大年龄和最小年龄但没有相应名称的代码。我不知道如何通过用户输入使其工作。我正在使用最新版本的Python和IDE PyCharm。

#name = input("Enter a series of names with corresponding ages:")

name = ["john", 25, "james", 32, "tanner", 62, "laura", 41, "christine", 21]
pairs = dict([tuple(name[i:i+2]) for i in range(0, len(name), 2)])

avg_salary = sum(pairs.values()) / len(pairs)
print("Average Age: %f" % (avg_age))

high_age = max(pairs.values())
print("Highest Age: %f" % (high_age))

low_age = min(pairs.values())
print("Lowest Age of: %f" % (low_age))

1 个答案:

答案 0 :(得分:0)

如果您使用的是Python3,则可以在dict上使用items()方法

#name = input("Enter a series of names with corresponding ages:")

import numpy as np

name = ["john", 25, "james", 32, "tanner", 62, "laura", 41, "christine", 21]
pairs = dict([tuple(name[i:i+2]) for i in range(0, len(name), 2)])

avg_age = np.mean(pairs.values())
print("Average Age: %.2f" % (avg_age))

high_age = max(pairs.items())
print("Highest Age: %i" % (high_age[1]) + " and their name is " + high_age[0])

low_age = min(pairs.items())
print("Lowest Age: %i" % (low_age[1]) + " and their name is " + low_age[0])

结果:

Average Age: 36.20
Highest Age: 62 and their name is tanner
Lowest Age: 21 and their name is christine

如果您使用的是Python 2,那么您可能会对这个问题感兴趣:What is the difference between dict.items() and dict.iteritems()?,尤其是第一个答案(可接受的答案)