如何打印字典的总和

时间:2017-10-08 05:25:16

标签: python dictionary

我正在尝试在字典中的每个列表上打印总和,但错误返回为TypeError:'int'对象不可迭代,不确定该怎么做。

def pass_bags(s,j):

  plane={}
  plane['Spirit']=s
  plane['JetBlue']=j
  return plane
def show_bags(bags, airline):
  for i in range(len(bags)):
      for x in bags[airline][i]:
          print (type (x))
s=[[5,6,7,7,8],[9,3,5]]
j=[[2,8,9,7],[2,3,5,6]]

需要说的是

On Spirit Airlines:
person 1 has 5 bags weighing 87 lbs
person 2 has 3 bags weighing 17 lbs

1 个答案:

答案 0 :(得分:0)

您需要将字典编入索引,以便仅对与该密钥关联的列表进行迭代。对于每个键,将每个子列表相加并打印详细信息。

def show_bags(bags, airline):
    for i, l in enumerate(bags[airline], 1):
        print('person {} has {} bags weighing {} lbs'.format(i, len(l), sum(l))