Python:嵌套的"for"循环 [英] Python: nested 'for' loops

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

问题描述

我想遍历所有n位数字,以便该数字的第二位数字始终小于或等于第一个数字,第三位小于或等于第二个数字,等等.例如:

I'd like to go through all n-digit numbers such that second digit of the number is always lower or equal to the first, third is lower or equal to the second etc. I can get this by writing a horrible code such as:

for i in range(10):
    for j in range(i+1):
        for k in range(j+1):

等,但是使用10位数字,我的代码开始看起来很恐怖,而且这笔写作很多,而且如果我要表扬其中的一些缩进,那么缩进会变得很恐怖.有没有一种很好的,简洁的方法来获取此信息?

etc., but with 10-digit numbers my code starts looking horrible, and also that's a lot of writing, and indentation get horrible if I want to commend few of those. Is there a nice, concise way of getting this?

https://projecteuler.net/problem=74让我检查1到100万之间的数字.不幸的是,这并没有我想象的那么简单-带有零的数字与内部带有零的数字被不同地对待,因此必须执行一些附加的魔术.无论如何,感谢大家的有见地的建议.

just so that people know why I'm bothering with this, https://projecteuler.net/problem=74 has me check numbers from 1 to one milion. Unfortunately, It's not as straightforward as I thought -- numbers with leading zeros are treated differently than the ones with zeros inside, so some additional magic had to be performed. Anyway, thanks to all for insightful suggestions.

推荐答案

可以使用itertools:

>>> for comb in itertools.combinations_with_replacement(range(9, -1, -1), 3):
        print comb

(9, 9, 9)
(9, 9, 8)
(9, 9, 7)
(9, 9, 6)
...
(4, 0, 0)
(3, 3, 3)
(3, 3, 2)
(3, 3, 1)
(3, 3, 0)
(3, 2, 2)
(3, 2, 1)
(3, 2, 0)
(3, 1, 1)
(3, 1, 0)
(3, 0, 0)
(2, 2, 2)
(2, 2, 1)
(2, 2, 0)
(2, 1, 1)
(2, 1, 0)
(2, 0, 0)
(1, 1, 1)
(1, 1, 0)
(1, 0, 0)
(0, 0, 0)


或者递归地,将越来越多的数字附加到足够的数量为止,这可以更直接地生成int对象而不是数字元组(不确定是否是您真正需要的):


Or recursively, appending more and more digits until enough, which can more directly produce int objects instead of digit tuples (not sure whether that's what you actually need):

def build(enough, prefix=0):
    if prefix >= enough:
        print(prefix)
        return
    for digit in range(prefix % 10 + 1) if prefix else range(1, 10):
        build(enough, prefix * 10 + digit)

演示(请注意,其中省略了"000",不确定是否要这样做):

Demo (note it leaves out "000", not sure whether you'd want that anyway):

>>> n = 3
>>> build(10**(n-1))
100
110
111
200
210
211
220
221
222
300
310
311
320
321
322
330
331
332
333
400
410
411
420

这篇关于Python:嵌套的"for"循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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