efficient matching of elements a list

O

omission9

Suppose I have a lists of tuples
A_LIST=[(1,6,7),(7,4,2),(7,9,2),(1,5,5),(1,1,1)]
and an int
i=1
What is the fastest way in python to get out all the tuples from the
list whose first element is equal to i?
A have a very large list and a simple
for a in A_LIST:
if a[0]==i:
#We have a match!!

Seems to be very slow and there must be some super quick pythonic way to
do this maybe?
Any avice would be much appreciated!!
 
P

Paul Rubin

omission9 said:
Suppose I have a lists of tuples
A_LIST=[(1,6,7),(7,4,2),(7,9,2),(1,5,5),(1,1,1)]
and an int
i=1
What is the fastest way in python to get out all the tuples from the
list whose first element is equal to i?

t = [x for x in A_LIST if x[0] == i]
Seems to be very slow and there must be some super quick pythonic way
to do this maybe?
Any avice would be much appreciated!!

Maybe there's some obscure faster way to do it but if you're really
in a hurry, use psyco or pyrex or write a C extension.
 
J

Josiah Carlson

Suppose I have a lists of tuples
A_LIST=[(1,6,7),(7,4,2),(7,9,2),(1,5,5),(1,1,1)]
and an int
i=1
What is the fastest way in python to get out all the tuples from the
list whose first element is equal to i?


t = [x for x in A_LIST if x[0] == i]

Before list comprehensions, we had to do it all with filter...
t = filter(lambda x:x[0]==i, A_LIST)

List comprehension seem to be around 33% faster. Long live list
comprehensions.

- Josiah
 
R

Rene Pijlman

omission9:
Suppose I have a lists of tuples
What is the fastest way in python to get out all the tuples from the
list whose first element is equal to i?

A list is not an efficient data structure for this query. Why don't you
design another data structure?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top