Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select value from list of tuples where condition

I have a list of tuples. Every tuple has 5 elements (corresponding to 5 database columns) and I'd like to make a query

select attribute1 from mylist where attribute2 = something 

e.g.

personAge = select age from mylist where person_id = 10 

Is it possible to query the list of tuples in some way?

like image 251
xralf Avatar asked Oct 24 '11 13:10

xralf


People also ask

How do you access elements in a list of tuples in Python?

In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item.

How do you filter a list based on a condition?

Short answer: To filter a list of lists for a condition on the inner lists, use the list comprehension statement [x for x in list if condition(x)] and replace condition(x) with your filtering condition that returns True to include inner list x , and False otherwise.

Does Index () work on tuples?

The tuple index() method helps us to find the index or occurrence of an element in a tuple. This function basically performs two functions: Giving the first occurrence of an element in the tuple. Raising an exception if the element mentioned is not found in the tuple.


1 Answers

If you have named tuples you can do this:

results = [t.age for t in mylist if t.person_id == 10] 

Otherwise use indexes:

results = [t[1] for t in mylist if t[0] == 10] 

Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.

like image 167
Steven Rumbalski Avatar answered Oct 16 '22 11:10

Steven Rumbalski