0

I have 2 list of elements and I am trying to do something like this:

for a in list1:
     for b in list2:
                if a.val == b.val:
                               #do xyz

Even if i use itertools product I am not sure how to then frame my if condition which needs an index from the set.

I know his is avery naive and bad way of doing which is costing my code to take up a lot of time. Can someone please help me with a faster and more efficient way of doing the same.

Piya
  • 11
  • 2
  • You are trying to perform an operation if two values in a list are equal? – idjaw Mar 27 '16 at 12:41
  • http://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches – Ajit kohir Mar 27 '16 at 12:44
  • You can use sets and their intersection. If order matters, look at the [OrderedSet](http://code.activestate.com/recipes/576694-orderedset/) recipe – Andrea Corbellini Mar 27 '16 at 12:46
  • Your code snippet compares every element in list `a` with every element is list `b`, which is `n^2` time complexity. Is this what you need, or do you intend to compare the first element in list `a` with the first element in list `b`, the second in list `a` with the second in list `b` and so on? – DeepSpace Mar 27 '16 at 12:46
  • No, you are right, it works that way, but you can write it down with less indentation: `for x in [ e for e in list1 if e in list2 ]: ...` (not really a duplicate btw.) – flaschbier Mar 27 '16 at 12:48
  • i have seen the examples already answered but i unsure how to place my double for loops in that way. Should i use set or itertools. – Piya Mar 27 '16 at 13:41
  • now I have for c in list1: for p in list2 if c.val == p.val: if I change it to for p in itertools.product(list1, list2): then how will i do c.val==p.val??? – Piya Mar 27 '16 at 13:48
  • @flaschbier: I tried to use the way you said: for x in [c for c in list1 if c in list2]: but then how will i fetch the value say like c.val1 and p.val1 like my original code. – Piya Mar 27 '16 at 14:03
  • Ok, forget the suggestion. I did not take the `.val` into account. – flaschbier Mar 27 '16 at 14:15
  • @idjaw let me know what you think – Piya Mar 27 '16 at 14:51
  • 1
    @Piya if the duplicate does not correspond to your question, then please update your question with your most up-to-date code. Provide detailed information on what it is you are *exactly* trying to do. Explain why it is not working and only then can the community assist in providing the needed help and vote to re-open this as a non duplicate. – idjaw Mar 27 '16 at 14:58

0 Answers0