代码之家  ›  专栏  ›  技术社区  ›  mightycode Newton

字典中的返回项不是元组

  •  -1
  • mightycode Newton  · 技术社区  · 3 年前

    我有一个excel文件,我相互累积每种水果的三个值。

    所以我这样做:

    def calulate_total_fruit_NorthMidSouth():
    
        import openpyxl
        import tabula
    
        excelWorkbook = openpyxl.load_workbook(path, data_only=True)
    
        sheet_factuur = excelWorkbook['Facturen ']
        new_list =[]
    
        fruit_sums = {
            'ananas': 0,
            'apple': 0,
            'waspeen': 0,
        }
    
        fruit_name_rows = {
            'ananas': [6, 7, 8],
            'apple': [9, 10, 11],
            'waspeen': [12, 13, 14],
        }
        array = [row for row in sheet_factuur.values]  # type: ignore
    
        # excel does not have a row 0
        for row_num, row_values in enumerate(array, 1):
            for fruit in ['ananas', 'apple', 'waspeen']:  # loop through specific fruits
                if row_num in fruit_name_rows[fruit]:
                    # index 4 is column 5 in excel
                    fruit_sums[fruit] += row_values[4]  # type: ignore
        return list(fruit_sums.items()) 
    

    但结果是:

    [('ananas', 3962), ('apple', 3304.08), ('waspeen', 3767.3999999999996)]
    

    但输出必须如下所示:

    ananas 3962
    apple 3304.08
    waspeen 3767.39
    

    如何将其与退货声明一起存档?

    2 回复  |  直到 3 年前
        1
  •  1
  •   Adrian Kurzeja    3 年前

    试试这样的方法:

    def f():
        x = {'a': 1, 'b': 2, 'c': 3}
        return '\n'.join(f'{a} {b}' for a, b in x.items())
    
    print(f())
    # a 1
    # b 2
    # c 3
    
        2
  •  0
  •   Cole Bechtel    3 年前

    不确定这是否是解决此问题的最佳方法,但您可以在打印前将其添加到代码中:

    mylist = list(fruit_sums.items())
    for i in mylist:
      newlist = list(i)
      for x in range(len(newlist)):
        newlist[x] = str(newlist[x])
    print(" ".join(newlist))