如何将一个值放在另一个列表中?

时间:2014-10-07 13:17:45

标签: python list python-3.x

我的程序需要接受来自用户的输入,但输入类似于Ted,24,因此每个输入都将用逗号分隔,我知道将它们放在列表中将是个好主意但我还需要得到平均年龄。到目前为止,这是我的代码:

namesAge = []
count = 0
ave = 0
total = 0

while True:
    mess=input("Enter name and age: ")
    if mess == "":
        print(namesAge)
        print ("We have ",count," names")
        print ("Total age is",total)
        break
    if "," in mess:
        namesAge.append(mess)
        count = count + 1
    else:
        print("invalid input")

1 个答案:

答案 0 :(得分:0)

namesAge = []

while True:
    mess=input("Enter name and age: ")
    if mess == "":
        print(namesAge)
        print ("We have {} names".format(len(namesAge)))
        print ("average age is {}".format(sum(namesAge)/len(namesAge))))
        break
    elif "," in mess:
        name, age = mess.split(',')
        namesAge.append(int(age))
    else:
        print("invalid input")