itertools.product
似乎给了你想要的东西。它经常用来代替嵌套
for
循环,但有一个方便的
repeat
这让你在这里的生活更轻松。
l = 3 # that's a lower-case L. Never use that in code, though, it looks like a 1.
digits = itertools.product(range(3), repeat=l)
# is equivalent to
def my_product():
"""the same as above itertools.product if l==3"""
for i in range(3):
for j in range(3):
for k in range(3):
yield (i, j, k)
my_digits = my_product() # YUCK!
这会产生
发电机
(注意:不是列表!)它产生了你想要的所有价值观
(0, 0, 0)
到
(2, 2, 2)
. 要列出一个列表,只需将其转换为一个。
digits = list(itertools.product(range(3), repeat=l)) # still a lower-case L. Still don't do this.
然后要比较数字,只需像任何二维列表一样使用索引。
first_value = digits[0]
first_digit = first_value[0]
assert first_digit == digits[0][0]
second_value = digits[1]
first_digit_of_second_value = second_value[0]
assert first_digit_of_second_value == digits[1][0]
if digits[0][0] == digits[1][0]:
# that's these two: v v
# digits == (0, 0, 0), (0, 0, 1), (0, 0, 2), ...
do_whatever_you_want()
如果你想特别输出
(0, 0, 0)
作为
000
,您可以为此编写函数:
def sprint_tuple(tup):
"""Takes a tuple of digits and pretty Sprints them.
>>> sprint_tuple((0, 0, 1))
'001'
"""
return ''.join([str(i) for i in tup])
然后把你的
digits
并分别打印:
>>> for tup in digits:
... print(sprint_tuple(tup))
000
001
002
010
...
222