python - 如何在python中循环未知数量的桶?
问题描述
我想获得这样的序列
a,b,c,.....,x,y,z,aa,ab,ac,....,az,ba,bb,....,bz,....,aaa,. ……,阿兹……,兹兹,……
依此类推,直到我达到给定的长度。
我的问题是我不知道如何编写无限数量的循环。
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
有人可以帮我解决这个问题吗?
解决方案
这是一个基于 itertools 的生成器:
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:])
输出:
['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']
推荐阅读
- javascript - PouchDB 和 Cloudant 之间复制期间出现 CustomPouchError
- c++ - C++ Vector 不同的形式和应用
- vba - 宏在幻灯片编辑器视图中运行正常但不是幻灯片视图
- android - 片段内的 Kotlin 按钮 onClickListener 事件
- sequelize.js - Feathers-Sequelize Where 语句和查询参数
- c# - .Net 控制台应用程序作为 CLI 命令
- c++ - 使用带有多个比较标准的 std::set 的容器
- sql - 参数不适用于 varchar
- r - 将字符向量转换为新的子字符串向量
- javascript - 将多维数组变成树状结构