使用 Python 的 itertools 的二维 table 索引生成器
Two dimensional table index generator using Python's itertools
我想将列表中的项目放置在 table 的顺序索引处,列数由输入控制。我知道如何通过在每列末尾递增或重置整数来以 "boring" 方式做到这一点,但我认为可能有更优雅的方式来做到这一点 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
这将生成将项目放置在以下 table 索引处的索引:
| 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维吗?
看起来你可以使用 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
为我们提供了行号。
我想将列表中的项目放置在 table 的顺序索引处,列数由输入控制。我知道如何通过在每列末尾递增或重置整数来以 "boring" 方式做到这一点,但我认为可能有更优雅的方式来做到这一点 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
这将生成将项目放置在以下 table 索引处的索引:
| 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维吗?
看起来你可以使用 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
为我们提供了行号。