gpt4 book ai didi

python - 在多个列表上循环以在 Python 3 中创建一条语句

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:22 26 4
gpt4 key购买 nike

如果这是一个重复的问题,我很抱歉。我花了一个小时试图找到答案并测试了一些理论但没有成功。在不发布我正在处理的整个代码的情况下,我将只发布代码片段。

基本上,我需要将这些 for 循环语句全部打印到一行中,以便为每位员工运行。

即“员工 Sam 31 岁,他们的职位是数据分析师,他们的年薪为 90,000 美元。他们 2017 年的奖金将为 2,700 美元。”

# Employee List
names = ['Sam', 'Chris', 'Jose', 'Luis', 'Ahmad']
ages = ['31', '34', '30', '28', '25']
jobs = ['Data Analyst', 'SEO Python Genius', 'Data Analyst', 'Interchange
Analyst', 'Data Analyst']
salaries = ['$90,000', '$120,000', '$95,000', '$92,000', '$90,000']
bonuses = ['$2,700', '$3,600', '$2,850', '$2,750', '$2,700']


# this for-loop goes through name list
for name in names:
print ("Employee %s" % name)

for age in ages:
print ("is %s" % age, "years old")

for job in jobs:
print (", their job title is %s" % job)

for salary in salaries:
print (" and they make %s" % salary, "annually.")

for bonus in bonuses:
print ("Their 2017 bonus will be %s." % salary)

最佳答案

您可以使用 zip通过并行列表共同迭代。

for name, age, job, salary, bonus in zip(names, ages, jobs, salaries, bonuses):
print ("Employee %s" % name)
print ("is %s years old" % age)
print (", their job title is %s" % job)
print (" and they make %s annually" % salary)
print ("Their 2017 bonus will be %s." % bonus)

这仍然会将消息的每个部分放在单独的行上,因为它们是单独的打印语句。相反,您可以将它们组合成一个 print:

for name, age, job, salary, bonus in zip(names, ages, jobs, salaries, bonuses):
print ("Employee %s is %s years old. Their job title is %s, and "
"they make %s annually. Their 2017 bonus will be %s."
%(name, age, job, salary, bonus))

关于python - 在多个列表上循环以在 Python 3 中创建一条语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44759611/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com