首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何在python中循环一个未知数量的桶?

我如何在python中循环一个未知数量的桶?
EN

Stack Overflow用户
提问于 2019-10-26 15:30:38
回答 2查看 229关注 0票数 2

我想得到这样的序列

a,b,c,.,x,y,z,aa,ab,ac,.,z,a,bb,.,bz,.,aaa,.,azz.,zzz,.

等等,直到我达到一个给定的长度。

我的问题是,我不知道如何编码无限多的循环。

代码语言:javascript
复制
abc = 'abcdefghijklmnopqrstuvwxyz'

def next_plate(i):
    for letter in abc:
        i += 1
        yield letter, i

num_plates = 10000
i = 0
all_plates = {}

for plate,i in next_plate(i):
    if i > num_plates:
        break
    all_plates[i] = plate

if i < num_plates:
    for plate_1, _ in next_plate(i):
        for plate_2,i in next_plate(i):
            if i > num_plates:
                break
            all_plates[i] = plate_1 + plate_2

if i < num_plates:
    for plate_1, _ in next_plate(i):
        for plate_2, _ in next_plate(i):
            for plate_3,i in next_plate(i):
                if i > num_plates:
                    break
                all_plates[i] = plate_1 + plate_2 + plate_3

有人能帮我吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-26 15:52:35

下面是一个基于迭代工具的生成器:

代码语言:javascript
复制
import itertools, string

def plates():
    n = 1
    while True:
        for plate in itertools.product(string.ascii_lowercase,repeat = n):
            yield ''.join(plate)
        n += 1

#test:

p = plates()
test = [next(p) for _ in range(10000)]
print(test[:30])
print(test[-30:])

产出:

代码语言:javascript
复制
['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']
['nsm', 'nsn', 'nso', 'nsp', 'nsq', 'nsr', 'nss', 'nst', 'nsu', 'nsv', 'nsw', 'nsx', 'nsy', 'nsz', 'nta', 'ntb', 'ntc', 'ntd', 'nte', 'ntf', 'ntg', 'nth', 'nti', 'ntj', 'ntk', 'ntl', 'ntm', 'ntn', 'nto', 'ntp']
票数 2
EN

Stack Overflow用户

发布于 2019-10-26 15:36:25

您需要使用while循环并将其设置为true(添加条件以在满足条件时中断)。我现在没有电脑,所以答案很简短。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58572173

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档