像excel列一样重复字母? [英] Repeating letters like excel columns?
问题描述
我想创建一个类似于 Microsoft Excel 中列字母的字符串列表.比如26列之后,接下来的列变成AA
、AB
、AC
等
我曾尝试使用模数运算符,但我最终得到了 AA
、BB
、CC
等...>
导入字符串pass_through_alphabet = 0对于 num, col in enumerate([_ for _ in range(40)]):如果数量 % 26 == 0:pass_through_alphabet += 1excel_col = string.ascii_uppercase[num%26] * pass_through_alphabet打印(数字,excel_col)0 安1 乙2 C3D...22 瓦23 X24岁25 Z26 AA27 BB28 CC...
您可以使用 itertools.product 用于此:
<预><代码>>>>导入迭代工具>>>列表(itertools.product(string.ascii_uppercase,repeat=2))[('A', 'A'), ('A', 'B'), ('A', 'C'), ('A', 'D'), ...将其与第一组字母组合,并加入对的结果:
<预><代码>>>>列表(... 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 from 仅在 python 3.3+ 中可用,但如果您使用的是 python 2,则可以使用 for 循环来生成每个项目.
>>>def excel_cols():...:n = 1...:而真:...: yield from (''.join(group) for group in itertools.product(string.ascii_uppercase, repeat=n))...:n += 1>>>列表(itertools.islice(excel_cols(),28))['一种','乙','C',...'X','你','Z','AA','AB']
I want to create a list of string that resemble the column letters in Microsoft Excel. For example, after 26 columns, the next columns become AA
, AB
, AC
, etc.
I have tried using the modulus operator, but I just end up with AA
, BB
, CC
, etc...
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
...
You can use itertools.product for this:
>>> import itertools
>>> list(itertools.product(string.ascii_uppercase, repeat=2))
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('A', 'D'), ...
Combining this with the first set of letters, and joining the pairs results in:
>>> 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']
To generalise, we define a generator which builds up bigger and bigger products. Note that the yield from is only available in python 3.3+, but you can just use a for loop to yield each item if you're on python 2.
>>> 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']
这篇关于像excel列一样重复字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!