计算一个元组的可数的行和列总数

2024-04-26 04:34:30 发布

您现在位置:Python中文网/ 问答频道 /正文

这需要在计算结果时yield。不应在任何时候存储所有数据。这应该支持大于内存的数据流。你知道吗

For each row add an int at the beginning that is the total of the row.

Once the entire input has been processed add a final row with the totals of every column in the input. This should include the initial total column and you should treat columns that are missing on a given row as zeros.

The row totals are the first column instead of the last (as is more common) because it makes rows of different length easier to handle.

例如:

    def func([(1,2,3), (4,5)]) = [(6,1,2,3),(9,4,5),(15,5,7,3)]

Tags: oftheaddinputthatisascolumn
1条回答
网友
1楼 · 发布于 2024-04-26 04:34:30

希望你能从中学到一些东西:

from itertools import izip_longest

def func(rows):
    totals = []
    for row in rows:
        row = (sum(row),) + row
        totals = [sum(col) for col in izip_longest(totals, row, fillvalue=0)]
        yield row
    yield tuple(totals)

>>> list(func([(1,2,3), (4,5)]))
[(6, 1, 2, 3), (9, 4, 5), [15, 5, 7, 3]]

此代码遍历所有行,生成一个元组,元组由求和列和原始列组成。你知道吗

^{}将当前行中的项与totals中相应的项配对,以保持每列的运行总数。^选择{}是因为它可以处理不同长度的行,并且可以为缺少的项提供填充值(本例中为0)。你知道吗

相关问题 更多 >