简体   繁体   English

如何制作连续的字母列表python(从az然后从aa,ab,ac等)

[英]How to make a continuous alphabetic list python (from a-z then from aa, ab, ac etc)

I would like to make a alphabetical list for an application similar to an excel worksheet.我想为类似于 Excel 工作表的应用程序制作一个按字母顺序排列的列表。

A user would input number of cells and I would like to generate list.用户将输入单元格数量,我想生成列表。 For example a user needs 54 cells.例如,用户需要 54 个单元格。 Then I would generate然后我会生成

'a','b','c',...,'z','aa','ab','ac',...,'az', 'ba','bb' 'a','b','c',...,'z','aa','ab','ac',...,'az','ba','bb'

I can generate the list from [ref]我可以从[ref]生成列表

 from string import ascii_lowercase
 L = list(ascii_lowercase) 

How do i stitch it together?我怎么把它缝在一起? A similar question for PHP has been asked here .已在此处询问了有关 PHP 的类似问题。 Does some one have the python equivalent?有人有 python 等价物吗?

Use itertools.product .使用itertools.product

from string import ascii_lowercase
import itertools

def iter_all_strings():
    for size in itertools.count(1):
        for s in itertools.product(ascii_lowercase, repeat=size):
            yield "".join(s)

for s in iter_all_strings():
    print(s)
    if s == 'bb':
        break

Result:结果:

a
b
c
d
e
...
y
z
aa
ab
ac
...
ay
az
ba
bb

This has the added benefit of going well beyond two-letter combinations.这具有远远超出两个字母组合的额外好处。 If you need a million strings, it will happily give you three and four and five letter strings.如果您需要一百万个字符串,它会很乐意为您提供三个、四个和五个字母的字符串。


Bonus style tip: if you don't like having an explicit break inside the bottom loop, you can use islice to make the loop terminate on its own:额外的样式提示:如果您不喜欢在底部循环中显式break ,您可以使用islice使循环自行终止:

for s in itertools.islice(iter_all_strings(), 54):
    print s

You can use a list comprehension.您可以使用列表理解。

from string import ascii_lowercase
L = list(ascii_lowercase) + [letter1+letter2 for letter1 in ascii_lowercase for letter2 in ascii_lowercase]

Following @Kevin 's answer :按照@Kevin 的回答:

from string import ascii_lowercase
import itertools

# define the generator itself
def iter_all_strings():
    size = 1
    while True:
        for s in itertools.product(ascii_lowercase, repeat=size):
            yield "".join(s)
        size +=1

The code below enables one to generate strings, that can be used to generate unique labels for example.下面的代码使人们能够生成字符串,例如,可用于生成唯一标签。

# define the generator handler
gen = iter_all_strings()
def label_gen():
    for s in gen:
        return s

# call it whenever needed
print label_gen()
print label_gen()
print label_gen()

I've ended up doing my own.我已经完成了自己的工作。 I think it can create any number of letters.我认为它可以创建任意数量的字母。

def AA(n, s):
    r = n % 26
    r = r if r > 0 else 26
    n = (n - r) / 26
    s = chr(64 + r) + s

    if n > 26: 
        s = AA(n, s)
    elif n > 0:
        s = chr(64 + n) + s

    return s

n = quantity | n = quantity | r = remaining (26 letters AZ) | r = remaining (26 letters AZ) | s = string

To print the list :打印列表:

def uprint(nc):
    for x in range(1, nc + 1):
        print AA(x,'').lower()

Used VBA before convert to python :在转换为 python 之前使用 VBA :

Function AA(n, s)

    r = n Mod 26
    r = IIf(r > 0, r, 26)
    n = (n - r) / 26
    s = Chr(64 + r) & s

    If n > 26 Then
        s = AA(n, s)
    ElseIf n > 0 Then
        s = Chr(64 + n) & s
    End If

    AA = s

End Function

Print the set of xl cell range of lowercase and uppercase charterers打印小写和大写租船者的一组 xl 单元格范围

Upper_case:大写:

from string import ascii_uppercase
import itertools
def iter_range_strings(start_colu):
    for size in itertools.count(1):
        for string  in itertools.product(ascii_uppercase, repeat=size):
            yield "".join(string)

input_colume_range = ['A', 'B']
input_row_range= [1,2]
for row in iter_range_strings(input_colume_range[0]):
    for colum in range(int(input_row_range[0]), int(input_row_range[1]+1)):
        print(str(row)+ str(colum))
    if row ==  input_colume_range[1]:
        break

Result:结果:

A1
A2
B1
B2

In two lines (plus an import):两行(加上一个导入):

from string import ascii_uppercase as ABC

count = 100
ABC+=' '
[(ABC[x[0]] + ABC[x[1]]).strip() for i in range(count) if (x:= divmod(i-26, 26))]

Wrap it in a function/lambda if you need to reuse.如果需要重用,请将其包装在函数/lambda 中。

Using neo's insight on a while loop.在 while 循环中使用 neo 的洞察力。 For a given iterable with chars in ascending order.对于给定的带有按升序排列的字符的迭代。 'abcd...'. 'A B C D...'。 n is the Nth position of the representation starting with 1 as the first position. n 是表示的第 N 个位置,从 1 开始作为第一个位置。

def char_label(n, chars):
    indexes = []
    while n:
        residual = n % len(chars)
        if residual == 0:
            residual = len(chars)
        indexes.append(residual)
        n = (n - residual)
        n = n // len(chars)
    indexes.reverse()
    label = ''
    for i in indexes:
        label += chars[i-1]
    return label

Later you can print a list of the range n of the 'labels' you need using a for loop:稍后您可以使用 for 循环打印您需要的“标签”范围 n 的列表:

my_chrs = 'abc'
n = 15
for i in range(1, n+1):
    print(char_label(i, my_chrs))

or build a list comprehension etc...或建立一个列表理解等...

code:代码:

alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for i in range(len(alphabet)):
    for a in range(len(alphabet)):
        print(alphabet[i] + alphabet[a])

result:结果:

aa
ab
ac
ad
ae
af
ag
ah
ai
aj
ak
al
am
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM