如何迭代列表中的每个名称以供用户输入?

2024-09-29 08:27:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个BMI计算器,我有一个人员列表,我的目标是遍历每个人,询问他们的身高体重,并将其存储在一个变量中。每次问他们,我都试图让他们说出自己的名字

recipients = ["John", "Dee", "Aleister", "Lilith", "Paul", "Reggy"]

for recipient in recipients:
    height = int(input("What is your height " + str(recipients)))
            

输出:

What is your height ['John', 'Dee', 'Aleister', 'Lilith', 'Paul', 'Reggy']

Tags: 列表your人员isjohnwhat计算器dee
3条回答

您甚至可以使用列表理解:

heights = [int(input(r + ', what is your height? ')) for r in recipients]

您可以使用for循环来实现这一点

recipients = ["John", "Dee", "Aleister", "Lilith", "Paul", "Reggy"]
heights = []
for recipient in recipients:
  heights.append(int(input(f"What is your height {recipient}")))

或者将len()与列表索引一起使用

recipients = ["John", "Dee", "Aleister", "Lilith", "Paul", "Reggy"]
heights = []
for i in range(len(recipients)):
  heights.append(int(input("What is your height " + recipients[i])))

您可以执行for循环,例如:

recipients = ["John", "Dee", "Aleister", "Lilith", "Paul", "Reggy"]
heights = []
for recipient in recipients:
  heights.append(int(input("What is your height " + recipient)))

相关问题 更多 >