473,480 Members | 1,874 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Searching through a list of tuples

I often find myself storing data in a list of tuples, and I want to ask
questions like "what is the index of the first tuple whose 3rd element
is x", or "give me the first tuple whose 2nd element is y".

I know I can do [elem for elem in lst if elem[3] == x][0] or (elem for
elem in lst if elem[2] == y).next() but it feels kinda ugly; is there a
better way?

(something like lst.index(x, key=..) or lst.find(y, key=..) would be
nice)

--
John.

Jul 21 '05 #1
5 1286
Repton wrote:
I often find myself storing data in a list of tuples, and I want to ask
questions like "what is the index of the first tuple whose 3rd element
is x", or "give me the first tuple whose 2nd element is y".

I know I can do [elem for elem in lst if elem[3] == x][0] or (elem for
elem in lst if elem[2] == y).next() but it feels kinda ugly; is there a
better way?

(something like lst.index(x, key=..) or lst.find(y, key=..) would be
nice)


If the latter form would make you happy, why not just write a simple
utility function that does what you want (by using the first technique,
if you wish), and then calling it will be as simple as lst.index(....)

And no, since you are basically doing a form of pattern matching, I
don't think there's a shortcut.

-Peter
Jul 21 '05 #2
Repton wrote:
I often find myself storing data in a list of tuples, and I want to ask
questions like "what is the index of the first tuple whose 3rd element
is x", or "give me the first tuple whose 2nd element is y".

I know I can do [elem for elem in lst if elem[3] == x][0] or (elem for
elem in lst if elem[2] == y).next() but it feels kinda ugly; is there a
better way?

(something like lst.index(x, key=..) or lst.find(y, key=..) would be
nice)

items = [(1, "a", 10), (2, "b", 20), (3, "c", 30)]
class Key(object): .... def __init__(self, key):
.... self.key = key
.... def __eq__(self, other):
.... return self.key(other)
.... items.index(Key(lambda x: x[2] == 20)) 1 items.index(Key(lambda x: x[1] == "c"))

2

A cleaner and probably faster solution would be to subclass list and
override index()/find().

Peter

Jul 21 '05 #3
Peter Otten wrote:
Repton wrote:
I often find myself storing data in a list of tuples, and I want to ask
questions like "what is the index of the first tuple whose 3rd element
is x", iter(n for n, elem in enumerate(lst) if elem[3] == x).next()
or "give me the first tuple whose 2nd element is y".

iter(elem in lst if elem[3] == x).next()

Does this look any better? At least it stops when the answer is found.

--Scott David Daniels
Sc***********@Acm.Org
Jul 21 '05 #4
Peter Otten wrote:
Repton wrote:
I often find myself storing data in a list of tuples, and I want to ask
questions like "what is the index of the first tuple whose 3rd element
is x", or "give me the first tuple whose 2nd element is y".
items = [(1, "a", 10), (2, "b", 20), (3, "c", 30)]
class Key(object): ... def __init__(self, key):
... self.key = key
... def __eq__(self, other):
... return self.key(other)
... items.index(Key(lambda x: x[2] == 20)) 1


Neat solution.

I'd add an extra kind of Key, since finding tuples where a given
position is equal to a given value seems to be the common case:
class EqualKey(Key): .... def __init__(self, pos, val):
.... super(EqualKey, self).__init__(lambda x: x[pos] == val)
.... items.index(EqualKey(2, 20))

1

Alan

Jul 21 '05 #5
Scott David Daniels wrote:
iter(elem*in*lst*if*elem[3]*==*x).next()

Does this look any better?**At*least*it*stops*when*the*answer*is*foun d.


Next time you'll recommend

if (a>b) == True:
# ...

Watch out, you're on a slippery slope here :-)

Peter

Jul 21 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2102
by: Thorsten Kampe | last post by:
I found out that I am rarely using tuples and almost always lists because of the more flexible usability of lists (methods, etc.) To my knowledge, the only fundamental difference between tuples...
24
3903
by: Mandus | last post by:
Hi there, inspired by a recent thread where the end of reduce/map/lambda in Python was discussed, I looked over some of my maps, and tried to convert them to list-comprehensions. This one I...
14
12243
by: Richard | last post by:
I have a large list of two element tuples. I want two separate lists: One list with the first element of every tuple, and the second list with the second element of every tuple. Each tuple...
7
5861
by: MTD | last post by:
Hello, I'm wondering if there's a quick way of resolving this problem. In a program, I have a list of tuples of form (str,int), where int is a count of how often str occurs e.g. L = would...
18
460
by: a | last post by:
can someone tell me how to use them thanks
7
1161
by: manstey | last post by:
Hi, I often use: a='yy' tup=('x','yy','asd') if a in tup: <...> but I can't find an equivalent code for:
11
16765
by: Noah | last post by:
I have a list of tuples I want to reverse the order of the elements inside the tuples. I know I could do this long-form: q = y = for i in y: t=list(t)
10
5124
by: rshepard | last post by:
While working with lists of tuples is probably very common, none of my five Python books or a Google search tell me how to refer to specific items in each tuple. I find references to sorting a list...
7
4422
by: Shafik | last post by:
Hello folks, I am an experienced programmer, but very new to python (2 days). I wanted to ask: what exactly is the difference between a tuple and a list? I'm sure there are some, but I can't...
0
7041
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7043
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7081
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6737
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5336
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4776
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
2984
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
563
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
179
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.