[英]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.