python 如何格式化dictionary.items,使其在逗号后返回2个标记?

tkqqtvp1  于 2022-11-27  发布在  Python
关注(0)|答案(1)|浏览(127)

我有一个Excel工作表,我从工作表中提取了一些值。但从文件工作表中提取的一些数字看起来像:

3767.3999999999996

它必须是:3767,39,逗号后面加两位小数.
我尝试使用此功能:

import openpyxl

def load_excel_file(self, file_name):
        excelWorkbook = openpyxl.load_workbook(filename=file_name, data_only=True)
        return excelWorkbook

def calulate_total_fruit_NorthMidSouth(self, file_name):

        # self.excelWorkbook
        sheet_factuur = self.load_excel_file(file_name)["Facturen "]

        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 "\n".join(f"{a} {b}" for a, b in "{:.2%}".format(fruit_sums.items()))

我尝试格式化return语句,但得到以下错误:

TypeError at /controlepunt
unsupported format string passed to dict_items.__format__

问题:如何正确格式化,使逗号后只有两个标记?

5vf7fwbs

5vf7fwbs1#

问题出在"{:.2%}".format(fruit_sums.items())上,但即使它工作了,你也会尝试迭代字符串上的key和value,这绝对不是这样的
您只需要将格式化逻辑应用于值

return "\n".join(f"{a} {b:.2f}" for a, b in fruit_sums.items())

相关问题