【问题标题】:Python function looping dictionariesPython函数循环字典
【发布时间】:2017-10-31 01:15:55
【问题描述】:

我正在尝试以特定格式输出员工信息。

dep_tup 是一个包含用户输入的所有不同部门名称的元组(无重复)。

dep_dict 是一个以部门为键的字典,而包含员工字典的列表作为与该键关联的值。

#Function that outputs the employees by department
def deps():
    for department in dep_tup:
        i = 0
        total = len(dep_dict[department])
        for i in range(len(dep_dict[department])):
            return "%s with %d employees\n" % (dep_dict[department], total)
            return "\n%s: %s, %s, $%f per year\n" % (dep_dict[department][i]["name"], dep_dict[department][i]["position"], dep_dict[department][i]["em_department"], dep_dict[department][i]["salary"])
            i += 1

例如,如果用户输入销售部门的 1 名员工和运营部门的 1 名员工,则应输出如下内容:

#Sales with 1 employees
#John Doe: sales lead, sales, $50000.00 per year
#Operations with 1 employees
#Jane Doe: technician, operations, $60000.00 per year

【问题讨论】:

  • 你不能连续返回语句...

标签: python python-3.x file dictionary


【解决方案1】:

我认为您只想打印,一旦您return 它返回要返回的内容并结束函数。此外,您不需要设置 i 并增加它,因为 for 循环会自动执行此操作。以下应该有效(但如果没有提供初始输入,我无法确定)

def deps():
    for department in dep_tup:
        total = len(dep_dict[department])
        for i in range(len(dep_dict[department])):
            print("%s with %d employees\n" % (dep_dict[department], total))
            print("\n%s: %s, %s, $%f per year\n" % (dep_dict[department][i]["name"], dep_dict[department][i]["position"], dep_dict[department][i]["em_department"], dep_dict[department][i]["salary"])

【讨论】:

  • 是的,这太完美了!我只需要将第一行打印放在 for 循环的顶部,这样它就不会为同一个部门重复该语句!但是我的 dep_dict[department] 正在打印与该部门关联的整个列表。我怎样才能打印部门名称?
  • 我必须能够查看您的字典才能提供帮助
猜你喜欢
  • 2018-10-06
  • 2018-02-22
  • 2014-02-14
  • 2018-12-04
  • 2014-06-02
  • 2017-12-04
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
相关资源
最近更新 更多