如果这是一个重复的问题,我很抱歉。我花了一个小时的时间试图找到答案,并测试了一些没有成功的理论。如果不发布我正在处理的整个代码,我就会发布代码片段。
基本上我需要将这些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)
答案 0 :(得分: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)
这仍然是消息的每个部分在一个单独的行上,因为它们是单独的打印语句。相反,您可以将它们合并为一个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))
答案 1 :(得分:1)
zip
这些在一起,理想情况下,使用格式字符串来减少整行,因为它们都使用相同的格式:
emps = zip(names, ages, jobs, salaries, bonuses)
fmt = ("Employee {} is {} years old, their job "
"title is {} and they make {} annually. "
"Their 2017 bonus will be {}.")
for emp in emps:
print(fmt.format(*emp))
相应地调整fmt
中的格式。
答案 2 :(得分:0)
如果您确定所有列表都具有相同的长度,您也可以按索引访问列表。
for i in range(len(names)):
print(names[i], ages[i], jobs[i], salaries[i], bonuses[i])
与使用zip
相比,我个人认为这使代码的可读性降低。