是否替换嵌套的循环... [英] Replace Nested For Loops... or not
问题描述
我有一个脚本,该脚本循环遍历四个(或更少)字符串.例如:
I have a script that loops through a series of four (or less) characters strings. For example:
aaaa
aaab
aaac
aaad
如果能够使用嵌套的for循环来实现它,就像这样:
If have been able to implement it with nested for loops like so:
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)
这种循环嵌套不好吗?如果是的话,哪种方法可以更好地完成我的工作?
Is this sort of loop nesting a bad thing, and if so, what would be a better way of accomplishing what I am doing?
推荐答案
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))
这将打印您要查找的所有 15018570
单词.如果您想要更多/更少的单词,只需更改 MAX_CHARS
变量.对于任何数量的字符,它仍然只有两个 for
,并且您不必重复自己的操作.并且可读性强.
That'll print all 15018570
words you're looking for. If you want more/less words just change the MAX_CHARS
variable. It will still have just two for
s for any number of chars, and you don't have to repeat yourself. And is pretty readable. .
这篇关于是否替换嵌套的循环...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!