Reputation: 1249
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.
Upvotes: 16
Views: 27702
Reputation: 6919
You can use python's list comprehensions to select and filter:
def find(tuples, term):
return [tuple for tuple in tuples if term in tuple]
Upvotes: 4
Reputation: 15936
This function will return a list of the tuples contain your search term. Here you go:
def find_in_tuples(tuples, term):
matching_set = []
for tuple in tuples:
if term in tuple:
matching_set.append(tuple)
return matching_set
>>> find_in_tuples(student_tuples, 'A')
[('john', 'A', 15)]
>>> find_in_tuples(student_tuples, 'B')
[('jane', 'B', 12), ('dave', 'B', 10)]
Upvotes: 0
Reputation: 601391
To find the first match only, you can use
def find(list_of_tuples, value):
return next(x for x in list_of_tuples if value in x)
This will raise StopIteration
if no matching record is found. To raise a more appropriate exception, you can use
def find(list_of_tuples, value):
try:
return next(x for x in list_of_tuples if value in x)
except StopIteration:
raise ValueError("No matching record found")
Upvotes: 10
Reputation: 37431
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)
Upvotes: 16