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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With