Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using list comprehension to search the first element of each element in a list

I'm comparing two lists to find if new data has been added to database 'polo'.

Originally the lists took the same form, however now 'excel' needs an accompanying coordinate to it's value. This was this orignal LC:

[x for x in polo_list if x not in excel]

I'm fascinated to hear about the different ways we can solve this (maybe I'm taking the wrong approach), here's a sample of the code now:

excel = [ ['a','a4'],['b','z4']]
polo = ['a','b','d']

a = [x for x in polo if x not in excel]

print 'new data! ', a

#should print,'new data!' ['d']

Thank you for your time

EDIT: Ah fantasic ! it's seems so simple now ! thank kind stackoverflow community, I freakin' love this site

like image 629
David Hancock Avatar asked Mar 14 '23 17:03

David Hancock


2 Answers

Just search in another comprehension:

a = [x for x in polo if x not in [item[0] for item in excel]]

It's better to save those values beforehand, though:

excel_first = [item[0] for item in excel]
a = [x for x in polo if x not in excel_first]

Or with a set:

excel_first = {item[0] for item in excel}
a = [x for x in polo if x not in excel_first]

Or, even better, with a dictionary:

excel = dict(excel)
a = [x for x in polo if x not in excel]

excel will then be a dictionary that you can use to quickly look up coordinates.

like image 67
TigerhawkT3 Avatar answered Apr 06 '23 01:04

TigerhawkT3


Here itertools.chain can help:

>>> from itertools import chain
>>> [x for x in polo if x not in chain(*excel)]
['d']
chain(*iterables) --> chain object

Return a chain object whose .__next__() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted.

like image 34
Mike Müller Avatar answered Apr 05 '23 23:04

Mike Müller