简体   繁体   English

从字典中返回项目而不是元组

[英]return items from dictionary not as tuple

I have an excel file and I accumulate thre values for each fruit sort with each other.我有一个 excel 文件,我为每个水果类别累积了三个值。

So I do it like this:所以我这样做:

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()) 

But the output is this:但是 output 是这样的:

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

But the output has to look like this:但是 output 必须如下所示:

ananas 3962
apple 3304.08
waspeen 3767.39

How to archive this with return statement?如何用返回语句归档这个?

Try something like this:尝试这样的事情:

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

Not sure if this is the best way to solve this problem but you could add this to your code before printing:不确定这是否是解决此问题的最佳方法,但您可以在打印前将其添加到您的代码中:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM