使用Python的itertools的二维表索引生成器

问题描述 投票:2回答:1

我想将列表中的项放在表的连续索引中,列数由输入控制。我知道如何通过在每列的末尾递增或重置整数来实现这种“无聊”的方式,但我认为使用Python的itertools库可能有更优雅的方法。

考虑这个清单:

items = ["Apple", "Orange", "Pear", "Strawberry", "Banana"]

这是无聊的方式:

def table_indexes(items, ncol):
    col = 0
    row = 0

    for item in items:
        yield (col, row)
        col += 1
        if col >= ncol:
            # end of row
            col = 0
            row += 1

这将产生将项放在下表索引处的索引:

| Apple  | Orange     |
| Pear   | Strawberry |
| Banana |            |

我想在itertools或其他地方找到一个能够产生一系列索引对的函数,其中每对中的一个索引重复循环一系列数字(列号),而另一个索引每次第一个循环时增加1重复?像这样:

def table_indexes(items, ncol):
    cols = ... # e.g. itertools.cycle(range(ncol))
    rows = ... # needs to be an iterator yielding sequences of [i]*ncol where i is the current row index
    yield zip(cols, rows):

解决方案可以扩展到N维吗?

python iterator generator sequence itertools
1个回答
1
投票

看起来你可以使用repeat

from itertools import chain, repeat

def table_indexes(items, ncol):
    cols = chain.from_iterable(repeat(range(ncol), len(items)//ncol + 1))
    for x, (col, item) in enumerate(zip(cols, items)):
    yield x//ncol, col, item

items = ["Apple", "Orange", "Pear", "Strawberry", "Banana"]
list(table_indexes(items, 3))

输出:

[(0, 0, 'Apple'),
 (0, 1, 'Orange'),
 (0, 2, 'Pear'),
 (1, 0, 'Strawberry'),
 (1, 1, 'Banana')]

更多细节,重复给我们一个列列表

repeat(range(ncol), len(items)//ncol + 1) - > [[0, 1, 2], [0, 1, 2]]

当我们循环遍历项目的枚举时,构造x // ncol给出了行的编号。

© www.soinside.com 2019 - 2024. All rights reserved.