我的作业问题之一是使用嵌套词典在一行上打印。我该怎么办?
答案 0 :(得分:0)
for employee in employees:
if employee["title"] == "Mr":
print(employee["employee_id"])
print(employee["lastname"], employee["firstname"])
答案 1 :(得分:0)
您可以使用print
的多个参数以空格分隔它们(可以通过sep
参数进行更改):
print(employees[0]["employee_id"], employees[1]["employee_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=" ")