2 回答
TA贡献1852条经验 获得超7个赞
for employee in employees:
if employee["title"] == "Mr":
print(employee["employee_id"])
print(employee["lastname"], employee["firstname"])
TA贡献1877条经验 获得超1个赞
您可以使用 的多个参数print用空格分隔它们(可以用sep参数更改):
print(employees[0]["employee_id"], employees[1]["employee_id"])
但是,如果您想打印出所有男性员工的 ID,您有几个不同的选择:
for 环形:
for employee in employees:
if employee["title"] == "Mr":
print(employee["employee_id"], end=" ")
参数解包:
male_employees = [employee["employee_id"] for employee in employees if employee["title"] == "Mr"]
print(*male_employees)
str.join
male_employees = [employee["employee_id"] for employee in employees if employee["title"] == "Mr"]
print(" ".join(male_employees))
特别是对于家庭作业问题,使用for循环的第一个选项是最直观的。
编辑:
要打印名称,您可以使用格式字符串:
for employee in employees:
if employee["title"] == "Mr":
print("{0}, {1}".format(employee["lastname"], employee["firstname"]), end=" ")
如果你想玩得更开心,这是一个选择:
for employee in employees:
if employee["title"] == "Mr":
print("{lastname}, {firstname}".format(**employee), end=" ")
添加回答
举报