python - checking if combination already exists from list comprehension -
as part of learning python have set myself challenges see various ways of doing things. current challenge create list of pairs using list comprehension. part 1 make list of pairs (x,y) must not same(x not equal y) , order matters((x,y) not equal (y,x)).
return [(x,y) x in listofitems y in listofitems if not x==y]
using existing code possible modify if (x,y) exists in list (y,x) exclude results? know compare items after words, want see how control can have list comprehension.
i using python 2.7.
you should use generator function here:
def func(listofitems): seen = set() #use set keep track of seen items, sets provide o(1) lookup x in listofitems: y in listofitems: if x!=y , (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)]
Comments
Post a Comment