【问题标题】:How to get all possible vectors of size n with elements [x,y]如何使用元素 [x,y] 获取所有可能的大小为 n 的向量
【发布时间】:2020-09-28 15:08:53
【问题描述】:

我的问题与to this one 类似,但我想找到包含[x,y,...] 元素的给定大小的所有可能向量。例如,给定一个列表[1,2],我如何找到所有可能包含元素12 且大小为3 的向量?在这种情况下是:

(1,1,1)
(1,1,2)
(1,2,1)
(2,1,1)
(1,2,2)
(2,1,2)
(2,2,1)
(2,2,2)

有什么优雅的方法可以做到这一点?我在想后续的for 循环并不是最好的方法。在我的真实案例中,我实际上正在寻找 $2^{8}$ 组合,因为我正在寻找具有 8 个元素的向量。

【问题讨论】:

  • 使用itertools.combinations
  • 使用itertools.product([1,2],repeat = 3)
  • 参见“itertools.product”
  • 好人,谢谢。我知道itertools.combinations,但无法让它工作。 itertools.product解决问题!
  • @JohnColeman 能否请您添加您的答案,因为它比我的要好。

标签: python list combinations


【解决方案1】:

感谢上面的 cmets,我得到了这样的工作:

[x for x in itertools.product(*[x for x in ((1,2),)*3])]
#out:
[(1, 1, 1),
 (1, 1, 2),
 (1, 2, 1),
 (1, 2, 2),
 (2, 1, 1),
 (2, 1, 2),
 (2, 2, 1),
 (2, 2, 2)]

【讨论】:

    【解决方案2】:

    以下工作(它也适用于 8 个元素):

    l=sum([list(set(itertools.permutations(i))) for i in list(itertools.combinations_with_replacement([1,2], 3))], [])
    print(l)
    

    输出:

    [(1, 1, 1), (1, 2, 1), (2, 1, 1), (1, 1, 2), (1, 2, 2), (2, 2, 1), (2, 1, 2), (2, 2, 2)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-17
      • 2020-07-19
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2014-07-27
      相关资源
      最近更新 更多