[英]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)]
使用product
和ifilter
以及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.