1

Wanted to get the difference between two list where list1 is

 l1 = range(10003, 10011)

And list2 i.e list of database object is`

 l2 = [<Model_obj: 10003 (3)>, <Model_obj: 10005 (5)>, <Model_obj: 10006 (6)>, <Model_obj: 10007 (7)>, <Model_obj: 10008 (8)>, <Model_obj: 10009 (9)>, <Model_obj: 10011 (11)>]

where <Model_obj: 10003 (3)> is having attributes like number, name, id etc. And 10003, 10005,... 10011 represents the values of number field of the model.

Now I want to get the list of values of missing numbers of second list i.e list1 while comparing with first list i.e list1 so in this case The Answer would be [10004, 10010] because this two number is missing in list2

I can able to do this while creating a number list of list2 using for loop and taking help of Get difference between two lists

I can achieve this by creating list3 as

l3 = set([obj.number for obj in l2])
response = set(l1) - l3

**Output**
{10004, 10010}

But is this a pythonic way to do this job?

Cœur
  • 37,241
  • 25
  • 195
  • 267
MaNKuR
  • 2,578
  • 1
  • 19
  • 31

2 Answers2

1

The solution you have in your question is quite pythonic. If you wanted to use more list comprehension:

l1 = list(range(10003, 10011))
l2 = [<Model_obj: 10003 (3)>, <Model_obj: 10005 (5)>, <Model_obj: 10006 (6)>,
      <Model_obj:10007 (7)>, <Model_obj: 10008 (8)>, <Model_obj: 10009 (9)>,
      <Model_obj: 10011 (11)>]

nums_not_found = [val for val in l1 if val not in [obj.number for obj in l2]]
BeetDemGuise
  • 954
  • 7
  • 11
  • Thanks but this will never produce the expected result as `l2` will always have number presents in `l1` but reverse may not be true. let me update my question a bit but please analyze again this if you have time. – MaNKuR May 23 '14 at 19:10
  • Thanks, This is another way to solve the problem but does not it cost more than using `set` as I mentioned in POST. – MaNKuR May 24 '14 at 05:40
0

Here's another efficient solution. It uses iterators when possible (ie: xrange), and displays the list of missing IDs at the end.

#!/usr/bin/env python

l1 = set( xrange(10003, 10011) )

l2 = [ dict(num=10003), dict(num=10008) ]

print 'Missing:', l1 - set( (obj['num'] for obj in l2) )

Example output:

Missing: set([10004, 10005, 10006, 10007, 10009, 10010])
johntellsall
  • 14,394
  • 4
  • 46
  • 40