簡體   English   中英

如何從 python 的列表中生成唯一的 arrays?

[英]How do you generate unique arrays from a list in python?

假設我在 python 中有一個簡單的列表:

a = [0,1,2]

如何從此列表中生成唯一的 arrays 以便我得到:

arr_gen = [[0,1],
           [1,2],
           [0,2]]

我試過用這種方式使用 numpy.random.choice:

>>> np.random.choice(a, (3,2), replace = False)

但我在下面收到以下錯誤:

>>> ValueError: Cannot take a larger sample than population when 'replace=False'

您可以嘗試使用內置的itertools模塊。

>>> import itertools
>>> a = [0, 1, 2]
>>> list(itertools.combinations(a, 2)
[(0, 1), (0, 2), (1, 2)]

您也可以在不使用itertools的情況下通過使用iterationsnumpy來解決這個問題

import numpy

def combinations(iterable, r): 
    char = tuple(iterable) 
    n = len(char) 
      
    if r > n: 
        return
      
    index = numpy.arange(r) 
    # retruns the first sequence  
    yield tuple(char[i] for i in index) 
      
    while True: 
          
        for i in reversed(range(r)): 
            if index[i] != i + n - r: 
                break
        else: 
            return
          
        index[i] += 1
          
        for j in range(i + 1, r): 
              
            index[j] = index[j-1] + 1
              
        yield tuple(char[i] for i in index) 
          
a = [0, 1, 2]
print([x for x in combinations(a, 2)]) 

Output:

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

方法一

只需combinations from itertools module即可。 因此,通過使用此代碼,您可以獲得所需的內容。

>>> from itertools import combinations
>>> print(list(map(list,combinations([0, 1, 2], 2))))
[[0, 1], [0, 2], [1, 2]]

方法2(獲取唯一列表)

在這個問題中,您還說您還需要生成唯一的 arrays,因此假設您的數組是 [0,1,1]。您可以使用這個,

>>> from itertools import combinations
>>> print(list(map(list,{*map(tuple,combinations([0, 1, 2], 2))})))
[[0, 1], [1, 1]]

在集合中刪除重復的項目。 所以在那之后你還必須將集合轉換為列表。

方法3(遞歸方法)

def myComb(lst):
    if len(lst) == 0:
        return []
    elif len(lst) == 1:
        return [lst]
    else:
        l = []
        for i in range(len(lst)):
            x = lst[i]
            xs = lst[:i] + lst[i+1:]
            for p in myComb(xs):
                l.append([x]+p)
        return l

ans=[]

for p in myComb([0,1,2]):
    p.pop()
    p.sort()
    if p not in ans:
        ans.append(p)

print(ans)

ans=[[0, 1], [0, 2], [1, 2]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM