使用Python的二维表索引生成器';s itertools
我希望将列表中的项目放置在表的顺序索引处,列数由输入控制。我知道如何通过在每列末尾递增或重置整数来实现这一点,这是一种“枯燥”的方法,但我认为使用Python的使用Python的二维表索引生成器';s itertools,python,iterator,generator,sequence,itertools,Python,Iterator,Generator,Sequence,Itertools,我希望将列表中的项目放置在表的顺序索引处,列数由输入控制。我知道如何通过在每列末尾递增或重置整数来实现这一点,这是一种“枯燥”的方法,但我认为使用Python的itertools库可能有一种更优雅的方法来实现这一点 考虑以下列表: items = ["Apple", "Orange", "Pear", "Strawberry", "Banana"] 以下是令人厌烦的方式: def table_indexes(items, ncol): col = 0 row = 0
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维吗?看起来您可以使用
输出:
[(0, 0, 'Apple'),
(0, 1, 'Orange'),
(0, 2, 'Pear'),
(1, 0, 'Strawberry'),
(1, 1, 'Banana')]
更多细节,重复给我们列的列表
重复(范围(ncol),长度(项目)//ncol+1)
-->[[0,1,2],[0,1,2]]
当我们循环遍历项的枚举时,结构
x//ncol
为我们提供了行数。看起来不错!我想知道Python的itertools
标准库中是否包含这样的方法。这可能是一个利基用例,但我认为这个问题会出现在许多不同的应用程序中
[(0, 0, 'Apple'),
(0, 1, 'Orange'),
(0, 2, 'Pear'),
(1, 0, 'Strawberry'),
(1, 1, 'Banana')]