Python:循环完成后配对字母 [英] Python: Pair alphabets after loop is completed

查看:66
本文介绍了Python:循环完成后配对字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过这个配对字母

导入字符串a=string.uppercase对于范围内的 i (0,30):打印 a[i%26]*(i/26+1)这将打印 A-Z 然后在 Z 之后它会像字符串一样打印 AA BB

但我需要把这个字符串像 AA AB AC AD AE 一样,直到在打印 A-Z 后定义范围然后结果会像打印 A-Z 然后 AA AB AC ....

解决方案

您可以利用 itertools 模块并使用生成器来非常干净地处理此问题:

from itertools import count, product, islice从字符串导入 ascii_uppercase定义多字母(seq):对于计数中的 n(1):对于产品中的 s(seq, repeat=n):产量 ''.join(s)

给予

<预><代码>>>>列表(islice(multiletters('ABC'), 20))['A', 'B', 'C', 'AA', 'AB', 'AC', 'BA', 'BB', 'BC', 'CA', 'CB', 'CC', 'AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB']>>>列表(islice(多字母(ascii_uppercase),30))['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', 'AA', 'AB', 'AC', 'AD']

如果您愿意,您可以制作一个对象并一个一个地获取它们:

<预><代码>>>>m = 多字母(ascii_uppercase)>>>下一个(米)'一种'>>>下一个(米)'乙'>>>下一个(米)'C'

[更新:我应该注意的是,我一直在 Python 和 Excel 之间传递数据——实际上我即将这样做——而且从不需要这个函数.但是,如果您对交换数据的最佳方式有具体问题,那么提出一个单独的问题可能比编辑这个问题要好,因为当前问题有多个答案.]

I tried to pair Alphabets by this

import string
a=string.uppercase
for i in range(0,30):
    print a[i%26]*(i / 26+1)

This will print A-Z and then after Z it will print AA BB like string

but i need to put this string like AA AB AC AD AE until the range is defined after printing A-Z then the result will be like print A-Z then AA AB AC ....

解决方案

You can take advantage of the itertools module and use a generator to handle this pretty cleanly:

from itertools import count, product, islice
from string import ascii_uppercase

def multiletters(seq):
    for n in count(1):
        for s in product(seq, repeat=n):
            yield ''.join(s)

gives

>>> list(islice(multiletters('ABC'), 20))
['A', 'B', 'C', 'AA', 'AB', 'AC', 'BA', 'BB', 'BC', 'CA', 'CB', 'CC', 'AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB']
>>> list(islice(multiletters(ascii_uppercase), 30))
['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', 'AA', 'AB', 'AC', 'AD']

and you can make an object and get them one by one, if you'd prefer:

>>> m = multiletters(ascii_uppercase)
>>> next(m)
'A'
>>> next(m)
'B'
>>> next(m)
'C'

[Update: I should note though that I pass data between Python and Excel all the time -- am about to do so, actually -- and never need this function. But if you have a specific question about the best way to exchange data, it's probably better to ask a separate question than to edit this one now that there are several answers to the current question.]

这篇关于Python:循环完成后配对字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆