【问题标题】:How can I make Python print all lists of given length with elements in a fixed finite set?如何让 Python 打印所有给定长度的列表以及固定有限集中的元素?
【发布时间】:2013-10-24 19:51:10
【问题描述】:

例如,我希望能够获取所有长度为 5 的列表,其中包含集合 {0,1,2,3} 中的元素。

我确信有一个简单的答案,但我被卡住了,我不知道该怎么做!

【问题讨论】:

  • itertools 是要使用的模块,但哪个功能取决于您想要什么。您希望[0,0,1,2,3][0,0,3,2,1] 都显示为输出吗?
  • 这是一个编程任务,而不是一个具体的问题。

标签: python list python-3.x


【解决方案1】:

您可能正在寻找itertools'combinations_with_replacement

list(itertools.combinations_with_replacement(range(4),2))
Out[18]: 
[(0, 0),
 (0, 1),
 (0, 2),
 (0, 3),
 (1, 1),
 (1, 2),
 (1, 3),
 (2, 2),
 (2, 3),
 (3, 3)]

(为简洁起见显示为n=2

【讨论】:

    【解决方案2】:

    如果您不将 (1,2)(2,1) 视为不同,请使用 roippi 的答案。如果你这样做了,itertools.product(如“笛卡尔积”)在这里工作:

    >>> import itertools
    >>> itertools.product(range(5), repeat=2)
    [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3)]
    

    【讨论】:

      【解决方案3】:

      这样做:

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

      Combinations_with_replacement 将捕获所有情况。它将 (a,b) 视为与 (a,b) 相同。在实践中,它只会输出有序的结果(例如(1,3),而不是(3,1))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-29
        • 2022-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-19
        相关资源
        最近更新 更多