python - for 循环不正确循环

标签 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')

最佳答案

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)

关于python - for 循环不正确循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41271318/

相关文章:

Python for 循环遍历列表

python - 将两个数据帧连接到第二个数据帧内的值

python - 如何从 GEANY (win 7) 运行脚本?

python - 将具有属性的节点从字典添加到图形中

python - 树莓派、Python、检测操作系统

python - 树hackerrank解决错误的故事

python - 调用 tkinter askopenfilename 方法后,打开文件对话框卡住

python-2.7 - 如何使用python向任何给定文件添加数字签名

python - pdb绕过错误/跳转失败: can only jump from a 'line' trace event

python - 删除 Pandas 中的单个和一系列列