for循环没有正确循环

时间:2016-12-21 20:24:20

标签: python python-3.x

这可能是一个简单的问题,但我的代码只在结尾处执行外部for循环,而在开始时执行一次。它应该遍历每个组合的每个组合

from itertools import permutations as p                                                                                                              
combos = p(['/','*','-','+'], 3)                                                                                          
numbers = p(['9','7','7','6'])                                                                                                                       
for y in numbers:                                                                                                                                    
    print(y)                                                                                                                                         
    for x in combos:                                                                                                           
        print(x)                                                                                                                                     

我做错了什么?它输出:

('9', '7', '7', '6')
('/', '*', '-')
('/', '*', '+')
('/', '-', '*')
('/', '-', '+')
('/', '+', '*')
('/', '+', '-')
('*', '/', '-')
('*', '/', '+')
('*', '-', '/')
('*', '-', '+')
('*', '+', '/')
('*', '+', '-')
('-', '/', '*')
('-', '/', '+')
('-', '*', '/')
('-', '*', '+')
('-', '+', '/')
('-', '+', '*')
('+', '/', '*')
('+', '/', '-')
('+', '*', '/')
('+', '*', '-')
('+', '-', '/')
('+', '-', '*')
('9', '7', '6', '7')
('9', '7', '7', '6')
('9', '7', '6', '7')
('9', '6', '7', '7')
('9', '6', '7', '7')
('7', '9', '7', '6')
('7', '9', '6', '7')
('7', '7', '9', '6')
('7', '7', '6', '9')
('7', '6', '9', '7')
('7', '6', '7', '9')
('7', '9', '7', '6')
('7', '9', '6', '7')
('7', '7', '9', '6')
('7', '7', '6', '9')
('7', '6', '9', '7')
('7', '6', '7', '9')
('6', '9', '7', '7')
('6', '9', '7', '7')
('6', '7', '9', '7')
('6', '7', '7', '9')
('6', '7', '9', '7')
('6', '7', '7', '9')

1 个答案:

答案 0 :(得分:6)

itertools.permutations生成一个迭代器。这意味着它可以被消费。消费后,后续循环将跳过它。如果将其转换为列表,您将可以继续访问其成员。

from itertools import permutations as p
combos = list(p(['/','*','-','+'], 3))
numbers = list(p(['9','7','7','6']))
for y in numbers:
    print(y)
    for x in combos:
        print(x)