gpt4 book ai didi

Python:我如何使用 itertools?

转载 作者:太空狗 更新时间:2023-10-29 22:02:53 27 4
gpt4 key购买 nike

我正在尝试制作一个包含 1 和 0 的所有可能变体的列表。例如,如果我只有两位数字,我想要一个这样的列表:

[[0,0], [0,1], [1,0], [1,1]]

但是如果我决定使用 3 位数字,我希望有一个这样的列表:

[[0,0,0], [0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0], [1,1,1]]

有人告诉我使用 itertools,但我无法让它按照我想要的方式工作。

>>> list(itertools.permutations((range(2))))
[(0, 1), (1, 0)]
>>> [list(itertools.product((range(2))))]
[[(0,), (1,)]]

有没有办法做到这一点?第二个问题,我如何找到这样的模块的文档?我只是在这里盲目地挥舞着

最佳答案

itertools.product(.., repeat=n)

>>> import itertools
>>> list(itertools.product((0,1), repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

Python Module Index包含标准库模块文档的链接。

关于Python:我如何使用 itertools?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17722989/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com