【问题标题】:How do I fill a list in python with elements from a specific set?如何使用特定集合中的元素填充 python 中的列表?
【发布时间】:2015-09-13 14:03:04
【问题描述】:

如果我有一组整数表示列表元素可以采用的值和给定长度的 python 列表。

我想用所有可能的组合填写列表。

示例

列出length=3my_set ={1,-1}

可能的组合

[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],
[-1,1,1],[-1,1,-1],[-1,-1,1],[-1,-1,-1]

我尝试使用随机类中的 random.sample 方法接近 但这无济于事。我做到了:

my_set=[1,-1]
from random import sample as sm
print sm(my_set,1)    #Outputs: -1,-1,1,1 and so on..(random)
print sm(my_set,length_I_require)        #Outputs**:Error

【问题讨论】:

    标签: python list random set combinations


    【解决方案1】:

    这就是itertools.product 的用途:

    >>> from itertools import product
    >>> list(product({1,-1},repeat=3))
    [(1, 1, 1), (1, 1, -1), (1, -1, 1), (1, -1, -1), (-1, 1, 1), (-1, 1, -1), (-1, -1, 1), (-1, -1, -1)]
    >>> 
    

    如果您希望将结果作为列表,您可以使用map 将元组的迭代器转换为列表 if 列表(在 python3 中,它返回一个迭代器,作为一种更有效的方式,您可以使用列表推导):

    >>> map(list,product({1,-1},repeat=3))
    [[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1]]
    

    在 python3 中:

    >>> [list(pro) for pro in product({1,-1},repeat=3)]
    [[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1]]
    >>> 
    

    【讨论】:

    • 正是我想要的。
    【解决方案2】:

    使用itertools.product() function

    from itertools import product
    
    result = [list(combo) for combo in product(my_set, repeat=length)]
    

    list() 调用是可选的;如果可以使用元组而不是列表,那么 result = list(product(my_set, repeat=length)) 就足够了。

    演示:

    >>> from itertools import product
    >>> length = 3 
    >>> my_set = {1, -1}
    >>> list(product(my_set, repeat=length))
    [(1, 1, 1), (1, 1, -1), (1, -1, 1), (1, -1, -1), (-1, 1, 1), (-1, 1, -1), (-1, -1, 1), (-1, -1, -1)]
    >>> [list(combo) for combo in product(my_set, repeat=length)]
    [[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1]]
    

    random.sample() 为您提供给定输入序列的随机子集;它不会产生所有可能的值组合。

    【讨论】:

      【解决方案3】:
      lst_length = 3
      my_set = {1,-1}
      result = [[x] for x in my_set]
      for i in range(1,lst_length):
          temp = []
          for candidate in my_set:
              for item in result:
                  new_item = [candidate]
                  new_item += item
                  temp.append(new_item)
          result = temp
      print result
      

      如果列表长度为 1,则结果是其元素等于集合的列表。列表长度每增加一,就可以通过将集合的每个元素附加到结果列表中来获得结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-04
        • 2016-10-04
        • 1970-01-01
        • 2013-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-29
        相关资源
        最近更新 更多