Python iterates over two lists when comparing items

I have two lists, for example x = [1,2,3,4,4,5,6,7,7] y = [3,4,5,6,7,8,9,10] , I want iterate over two lists when comparing items. For those that match, I would like to call some function and remove them from the lists, in this example I should get x = [1,2] and y = [8,9,10]. Sets will not work for this problem due to my data type and comparison operator.

 for i in x: for j in y: if i ==j: callsomefunction(i,j) remove i, j from x and y respectively 
+8
python list
source share
4 answers

Edit: After the person asking the question simply did not know about __hash__ , I provided this information in a comment:

To use sets, do __hash__ . Therefore, if obj1 == obj2 , when obj1.a == obj2.a and ob1.b == obj2.b , __hash__ should be return hash((self.a, self.b)) , and your sets will work as expected.

This solved their problem, and they switched to using sets.

The rest of this answer is now deprecated, but it is still correct (but terribly inefficient), so I will leave it here.


This code does what you want. In the end, newx and newy are nonoverlapping elements of x and y in particular.

 x = [1,2,3,4,4,5,6,7,7] y = [3,4,5,6,7,8,9,10] # you can leave out bad and just compare against # x at the end if memory is more important than speed newx, bad, newy = [], [], [] for i in x: if i in y: callsomefunction(i) bad.append(i) else: newx.append(i) for i in y: if i not in bad: newy.append(i) print newx print newy 

However, I know, without even seeing your code, that this is the wrong way to do this. You can, of course, do this with kits, but if you do not want this, then it is up to you.

+4
source share

Ok, drop my post, I didn’t see the point when you mentioned that the sets will not work.

However, if you're fine with a little work, you can use classes to make the operators work as they expected.

I think the most "pythonic" way to do this is to use kits. Then you can:

 x = set([1,2,3,4,4,5,6,7,7]) y = set([3,4,5,6,7,8,9,10]) for item in x.intersection(y): #y.intersection(x) is fine too. my_function(item) #You could use my_function(item, item) if that what your function requires x.remove(item) y.remove(item) 

I think kits are also more efficient than lists for this kind of job when it comes to performance (although this may not be your top priority).

In the clip you can also use:

 x,y = x.difference(y), y.difference(x) 

This effectively removes elements located in x and y from x and y.

+3
source share

Try the following:

 for i in x: if i in y: callsomefunction(i) x.remove(i) y.remove(i) 

EDIT: Updated Answer

+1
source share

how about this:

 import itertools x = [1,2,3,4,4,5,6,7,7] y = [3,4,5,6,7,8,9,10] output = map(somefunction, itertools.product(x,y)) 
-one
source share

All Articles