gpt4 book ai didi

python - 在 Python 中设置产品

转载 作者:太空狗 更新时间:2023-10-29 21:27:34 25 4
gpt4 key购买 nike

集合 S 的 n 个副本的乘积表示为 Sn。例如,{0, 1}3 是所有 3 位序列的集合:

{0,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)}

在 Python 中复制这个想法的最简单方法是什么?

最佳答案

在 Python 2.6 或更新版本中,您可以使用 itertools.product使用可选参数 repeat:

>>> from itertools import product
>>> s1 = set((0, 1))
>>> set(product(s1, repeat = 3))

对于旧版本的 Python,您可以使用文档中的代码实现 product:

def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)

关于python - 在 Python 中设置产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3271931/

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