【问题标题】:Generate a list of length n with m possible elements生成包含 m 个可能元素的长度为 n 的列表
【发布时间】:2010-10-05 01:19:20
【问题描述】:

我需要在 Python 中生成大量列表。每个列表的长度为 13,每个元素有 4 个可能的值。这些是 [1, -1, i, -i],但也可以是任何值。

因此,鉴于主题中的信息,我应该得到 4 * 4 * 4 ... * 4 = 4^13 = 67,108,864 个列表,或者更一般地说,m^n。

我尝试了 Python 的 itertools 中的 combination_with_replacement 方法,但是使用以下代码我只能得到 560 个结果。

c = it.combinations_with_replacement([1,-1,np.complex(0,1), np.complex(0,-1)], 13)
print list(c)

我知道组合不关心顺序,所以这个结果可能是正确的。但是,当我改用 permutations 方法时,我只能选择第二个参数

知道如何做到这一点吗?

谢谢!

【问题讨论】:

    标签: python permutation combinations itertools


    【解决方案1】:

    我想你想要

    y = itertools.product((1, -1, 1j, -1j), repeat=13)
    


    然后,顺便说一句,print sum(1 for x in y) 打印出67108864,正如你所期望的那样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      相关资源
      最近更新 更多