【问题标题】:Finite permutations of a list python列表python的有限排列
【发布时间】:2019-04-13 12:03:47
【问题描述】:

我有一个列表,想生成有限数量的排列,没有重复的元素。

itertools.permutations(x)

给出所有可能的排序,但我只需要特定数量的排列。 (我的初始列表包含约 200 个元素 => 200!将花费不合理的时间,而且我不需要所有元素)

到目前为止我做了什么

def createList(My_List):
    New_List = random.sample(My_List, len(My_List))
    return New_List

def createManyList(Nb_of_Lists):
    list_of_list = []
    for i in range(0, Nb_of_Lists):
        list_of_list.append(createList())
    return list_of_list

它正在工作,但我的 List_of_list 不会有唯一的排列,或者至少我对此没有任何保证。

有什么办法可以做到吗?谢谢

【问题讨论】:

标签: python permutation itertools


【解决方案1】:

只需使用islice,它允许您从可迭代对象中获取多个元素:

from itertools import permutations, islice

n_elements = 1000

list(islice(permutations(x), 0, 1000))

这将返回(第一个)1000 个排列的list

这样做的原因是permutations 返回一个迭代器,它是一个对象,它生成值以在需要时返回,而不是立即返回。因此,这个过程是这样的:

  1. 调用函数(在本例中为list)请求来自islice 的下一个值
  2. islice 检查是否返回了 1000 个值;如果没有,它会从permutations 中询问下一个值
  3. permutations 按顺序返回下一个值

因此,不需要生成完整的排列列表;我们只取所需数量。

【讨论】:

  • 这是最好的解决方案。您可能想添加一个简短的解释,为什么生成器在 python 中是高效的,并且实际上并未创建所有排列,然后过滤到 1000。
  • 是的,这就是要走的路!
【解决方案2】:

你可以这样做:

i = 0
while i < Nb_of_Lists:
    if createlist() not in list_of_lists:
        list_of_list.append(createList())
    else:
        i -= 1

这将检查该排列是否已被使用。

【讨论】:

    【解决方案3】:

    您不需要滚动自己的排列。一旦你足够了,你就停止生成器:

    # python 2.7
    import random
    import itertools
    def createList(My_List):
        New_List = random.sample(My_List, len(My_List))
        return New_List
    
    x = createList(xrange(20))
    def getFirst200():
        for i, result in enumerate(itertools.permutations(x)):
            if i == 200:
                raise StopIteration
            yield result
    
    print list(getFirst200()) # print first 200 of the result
    

    这比“生成全套然后取前 200 个”方法更快,内存效率更高

    【讨论】:

    • @gmds 建议的islice() 方法更简洁。
    • 请注意,在 Python 3.6 中,generator 中的 raise StopIteration 将引发 DeprecationWarning;在 Python 3.7 中,它将引发 RuntimeError
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2010-11-09
    相关资源
    最近更新 更多