Sad*_*Dip 1 python combinations tuples list python-itertools
我一直在尝试创建一个脚本,其中将打印列表的每个可能组合[其中 (1,2) 和 (2,1) 将被视为不同的条目]。例如:
c = [1,2]
# do something magical
print(c with magical stuff)
>>>[(1), (2), (1, 1), (1, 2), (2, 1), (2, 2)]
Run Code Online (Sandbox Code Playgroud)
我试过 itertools.permutations。它显示输出为 >>> () (1,) (2,) (1, 2) (2, 1)。但是,它不包括 (1, 1) 和 (2,2)
任何帮助将不胜感激。我是编码新手(我非常流利地打印“Hello World!”虽然:3)
尝试itertools.product:
def foo(l):
yield from itertools.product(l)
yield from itertools.product(l, l)
Run Code Online (Sandbox Code Playgroud)
for x in foo([1, 2]):
print(x)
(1,)
(2,)
(1, 1)
(1, 2)
(2, 1)
(2, 2)
Run Code Online (Sandbox Code Playgroud)
请注意,该yield from语法从 python3.3 开始可用。