循环并返回字典中的所有值

时间:2015-08-13 23:41:40

标签: python

每当我执行下面的代码时,它只返回一个total_hours而不是值数组中的所有小时

worker_hours = {'John': [8,8,4,3,8],
                'Leo': [5,6,7,8,9],
                'Sammy': [4,5,6,8,8],
                'Ken': [8,8,8,8,8]}

def calc_check(worker_list):
    worker = ''
    total_hours = 0
    for worker in worker_list:
        total_hours = sum(worker_list[worker]) * 13
    return total_hours

print(calc_check(worker_hours))

我如何打印出密钥和列表中的总小时数*支付新线路?到目前为止我有:

def calc_check(worker_list):
  workers = ''
  total_hours = 0
  for worker in worker_list:
     total_hours = sum(worker_list[worker])
     pay = total_hours * 13
     return print("{}'s total check amount is {}".format(worker,pay))

print(calc_check(worker_hours))

1 个答案:

答案 0 :(得分:1)

您每次替换 var xx = x.CallNewAsyncMethod(); xx.Wait();//blocks until CallNewAsyncMethod completes 值:

total

如果您想表达式的结果添加到正在运行的总计中,请使用添加或更好的扩充作业:

for worker in worker_list:
    total_hours = sum(worker_list[worker]) * 13

请注意,您不必预定义for worker in worker_list: total_hours += sum(worker_list[worker]) * 13 。你可以遍历worker(这实际上是一个字典,而不是列表),你可以用嵌套表达式求和:

worker_list

或通过链接它们来汇总所有列表编号,然后将该总和乘以13:

def calc_check(workers):
    return sum(sum(hours) * 13 for hours in workers.values())

演示:

from itertools import chain

def calc_check(workers):
    return sum(chain.from_iterable(workers.values())) * 13