Mat*_* PA 6 python loops for-loop nested-loops
我有一个循环通过一系列四个(或更少)字符串的脚本.例如:
aaaa
aaab
aaac
aaad
Run Code Online (Sandbox Code Playgroud)
如果能够使用嵌套的for循环实现它,如下所示:
chars = string.digits + string.uppercase + string.lowercase
for a in chars:
print '%s' % a
for b in chars:
print '%s%s' % (a, b)
for c in chars:
print '%s%s%s' % (a, b, c)
for d in chars:
print '%s%s%s%s' % (a, b, c, d)
Run Code Online (Sandbox Code Playgroud)
这种循环是一种坏事,如果是这样,那么完成我正在做的事情的更好方法是什么?
nos*_*klo 15
import string
import itertools
chars = string.digits + string.letters
MAX_CHARS = 4
for nletters in range(MAX_CHARS):
for word in itertools.product(chars, repeat=nletters + 1):
print (''.join(word))
Run Code Online (Sandbox Code Playgroud)
那将打印出15018570你正在寻找的所有单词.如果你想要更多/更少的单词只需更改MAX_CHARS变量.for对于任何数量的字符,它仍然只有两个s,你不必重复自己.而且很可读..
我将把我的答案提交为最具可读性和最低可扩展性:)
import string
chars = [''] + list(string.lowercase)
strings = (a+b+c+d for a in chars
for b in chars
for c in chars
for d in chars)
for string in strings:
print string
Run Code Online (Sandbox Code Playgroud)
编辑:实际上,这是不正确的,因为它将产生长度<4的所有字符串的重复.从chars数组中删除空字符串只会生成4个字符串.
通常我会删除这个答案,但如果你需要生成相同长度的字符串,我仍然会喜欢它.