【问题标题】:Create a vector given N input of names and ages python给定 N 个输入的姓名和年龄 python 创建一个向量
【发布时间】:2016-09-29 05:02:14
【问题描述】:

我需要创建一个程序,将多个姓名和年龄条目作为输入。然后我希望它返回那些年龄值高于所有条目平均年龄的条目的名称和年龄。 例如:

input( "Enter a name: ") Albert   
input( "Enter an age: ") 16

input( "Enter a name: ") Robert   
input( "Enter an age: ") 18

input( "Enter a name: ") Rose  
input( "Enter an age: ") 20

The average is = 18
Rose at 20 is higher than the average. 

我该怎么做?

【问题讨论】:

    标签: python dictionary vector


    【解决方案1】:
    answers = {} 
    # Use a flag to indicate that the questionnaire is active. 
    questions_active = True 
    while questions_active: 
    # Ask for the person's name and response.
        name = raw_input("\nEnter a name: ") 
        response = raw_input("Enter an age: ")
    # Store the response in the dictionary: 
        answers[name] = int(response)
    # Check if anyone else is going to take the questionnaire. 
        repeat = raw_input("Would you like to let another person respond? (yes/ no) ") 
        if repeat == 'no': 
            questions_active = False
    
    average_age = sum(answers.values())/float(len(answers))
    print("The average is " + str(average_age))
    # Questionnaire is complete. Show the results. 
    for name, response in answers.items():
        if response > average_age:
            print(name.title() + " at " + str(response) + " is higher than the average.")
    

    此答案基于“Python Crash Course: A Hands-On, Project-Based Introduction to Programming”一书中的类似示例https://www.nostarch.com/pythoncrashcourse

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多