Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python how to find elements in a list of lists based on a key that is an element of the inner list?

Tags:

python

Suppose I have a list of lists or a list of tuples, whichever can solve my problem more efficiently. Eg:

student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]

The task is to find an element in the main list based on a key that is any element of the inner list or tuple. Eg:

Using the list above:

find(student_tuples, 'A')

or

find(student_tuples, 15)

would both return

('john', 'A', 15)

I'm looking for an efficient method.

like image 548
kadam Avatar asked Apr 13 '11 17:04

kadam


1 Answers

I would use filter() or a list comprehension.

def find_listcomp(students, value):
    return [student for student in students if student[1] == value or student[2] == value]

def find_filter(students, value):
    return filter(lambda s: s[1] == value or s[2] == value, students) 
like image 190
Daenyth Avatar answered Oct 21 '22 04:10

Daenyth