Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python iterate over the two lists while comparing items

Tags:

python

list

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

for i in x:
  for j in y:
    if i ==j:
       callsomefunction(i,j)
       remove i, j from x and y respectively
like image 829
user739807 Avatar asked Aug 19 '11 13:08

user739807


People also ask

How do you compare items in a list in Python?

sort() and == operator. The list. sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.


1 Answers

Edit: After discovering the person asking the question simply didn't know about __hash__ I provided this information in a comment:

To use sets, implement __hash__. So 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.

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

The rest of this answer is now obsolete, but it's still correct (but horribly inefficient) so I'll leave it here.


This code does what you want. At the end, newx and newy are the non-overlapping items of x and y specifically.

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 certainly do it with sets, but if you don't want to, that's up to you.

like image 93
agf Avatar answered Nov 15 '22 11:11

agf