for循环使用多个列表在Python 3中创建一个语句

Sam*_*mer 3 python python-3.x

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

基本上我需要将这些for循环语句打印成一行来为每个员工运行.

即'员工山姆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)
Run Code Online (Sandbox Code Playgroud)

khe*_*ood 7

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

这仍然是消息的每个部分在一个单独的行上,因为它们是单独的打印语句.相反,您可以将它们组合成一个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))
Run Code Online (Sandbox Code Playgroud)