我想创建一个类似于 Microsoft Excel 中列字母的字符串列表。例如,在 26 列之后,接下来的列变为 AA
、AB
、AC
等。
我试过使用模数运算符,但我最终得到的是 AA
、BB
、CC
等...
import string
passes_through_alphabet = 0
for num, col in enumerate([_ for _ in range(40)]):
if num % 26 == 0:
passes_through_alphabet += 1
excel_col = string.ascii_uppercase[num%26] * passes_through_alphabet
print(num, excel_col)
0 A
1 B
2 C
3 D
...
22 W
23 X
24 Y
25 Z
26 AA
27 BB
28 CC
...
最佳答案
您可以使用 itertools.product为此:
import string
import itertools
list(itertools.product(string.ascii_uppercase, repeat=2))
输出:
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('A', 'D'), ...
将其与第一组字母组合,并连接成对结果:
list(
itertools.chain(
string.ascii_uppercase,
(''.join(pair) for pair in itertools.product(string.ascii_uppercase, repeat=2))
))
输出:
['A', 'B', 'C', .. 'AA', 'AB', 'AC' .. 'ZZ']
总而言之,我们定义了一个生成越来越大的产品的生成器。请注意,yield 仅在 python 3.3+ 中可用,但如果您使用的是 python 2,则可以只使用 for 循环来生成每个项目。
def excel_cols():
n = 1
while True:
yield from (''.join(group) for group in itertools.product(string.ascii_uppercase, repeat=n))
n += 1
list(itertools.islice(excel_cols(), 28))
输出
['A', 'B', 'C', ... 'X', 'Y', 'Z','AA', 'AB']
关于python - 像 excel 列一样重复字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42176498/