簡體   English   中英

檢查列表理解中是否已存在組合

[英]checking if combination already exists from list comprehension

作為學習Python的一部分,我為自己設定了一些挑戰,以便了解各種做事方式。 我目前的挑戰是使用列表理解創建一對對列表。 第一部分是制作一對列表,其中(x,y)必須不相同(x不等於y)和順序重要((x,y)不等於(y,x))。

return [(x,y) for x in listOfItems for y in listOfItems if not x==y]

使用我現有的代碼是可以修改它,所以如果(x,y)已經存在於列表中(y,x)將其從結果中排除? 我知道我可以在單詞之后比較項目,但我想看看你對列表理解有多少控制權。

我使用的是Python 2.7。

你應該在這里使用生成器函數:

def func(listOfItems):
    seen = set()  #use set to keep track of already seen items, sets provide O(1) lookup  
    for x in listOfItems:
        for y in listOfItems:
            if x!=y and (y,x) not in seen:
                seen.add((x,y)) 
                yield x,y

>>> lis = [1,2,3,1,2]
>>> list(func(lis))
[(1, 2), (1, 3), (1, 2), (2, 3), (1, 2), (1, 3), (1, 2), (2, 3)]
def func(seq):
    seen_pairs = set()
    all_pairs = ((x,y) for x in seq for y in seq if x != y)
    for x, y in all_pairs:
        if ((x,y) not in seen_pairs) and ((y,x) not in seen_pairs):
            yield (x,y)
        seen_pairs.add((x,y))

或者,您也可以使用生成器表達式 (此處: all_pairs ),它類似於列表all_pairs ,但是延遲評估。 它們非常有用,特別是在迭代組合, 產品等時。

使用productifilter以及itertools中unique_everseen配方

>>> x = [1, 2, 3, 1, 2]
>>> x = product(x, x)
>>> x = unique_everseen(x)
>>> x = ifilter(lambda z: z[0] != z[1], x)
>>> for y in x:
...     print y
... 
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)

暫無
暫無

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

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