问题描述
我创建了一个函数,可以生成一个连续递增的字母列表。 A,B,C ......,Z.在Z之后,它转到AA,AB,AC ...... AZ。这种模式重复。这类似于MS Excel的列名。目前,此函数生成一个有限的字母表列表。
I've created a function that generates a list of alphabets incrementing continuously. A, B, C ..., Z. After Z, it goes to AA, AB, AC ...AZ. This pattern repeats. This is similar to MS Excel's column names. At the moment, this function generates a finite list of alphabets.
_column_name_generator() = ['A', 'B', ..., 'AA', 'AB', ..., 'BA', 'BB', ..., 'CV']
我可以然后结合一些有限列表迭代它,例如0-10。请参阅下面的代码。我想要的是创建一个生成器,它将给我一个无限长的增量字母表列表。
I can then iterate over it in conjunction with some finite list, e.g. 0-10. See my code below. What I'd like is to create a generator that will give me an infinitely long list of incrementing alphabets.
import string
def _column_name_generator():
column_names = []
for x in range(0, 100):
if x < 26:
column_names.append(string.ascii_uppercase[x % 26])
else:
column_names.append(column_names[x/26 - 1] + string.ascii_uppercase[x % 26])
return column_names
container = []
for column_name, num in zip(_column_name_generator(), range(0, 10)):
container.append(column_name + str(num))
print _column_name_generator()
print container
container = ['A0', 'B1', 'C2', 'D3', 'E4', 'F5', 'G6', 'H7', 'I8', 'J9']
推荐答案
每次产量 column_names
的最后一个元素,并使用 itertools.count
而不是范围
提供无限增加:
Yield column_names
's last element every time, and use itertools.count
instead of range
to provide infinite increase:
import itertools
def _column_name_generator():
column_names = []
for x in itertools.count():
if x < 26:
column_names.append(string.ascii_uppercase[x % 26])
else:
column_names.append(column_names[x/26 - 1] + string.ascii_uppercase[x % 26])
yield column_names[-1]
一个更好的解决方案,改变原始代码,但在 column_names
的内存消耗列表中消除需要,将
A better solution, altering the original code but dismissing the need in a memory consuming list of column_names
, would be
import itertools, string
def _column_name_generator():
for i in itertools.count(1):
for p in itertools.product(string.ascii_uppercase, repeat=i):
yield ''.join(p)
它基本上遍历长度 i
的产品,当我逐渐增加时,从 1开始,大写的ascii字母(每个可能的序列)
( A
, B
, C
)。
it basically iterates over the product of length i
the uppercase ascii letters (every sequence possible) when i is gradually increasing, starting from 1
(A
, B
, C
).
这篇关于如何创建一个无限迭代器来生成递增的字母模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!