如何使用Python根据内层列表中的元素找到列表中的元素?
假设我有一个包含多个列表的列表,或者包含多个元组的列表,哪种方式能更有效地解决我的问题都可以。比如:
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
我的任务是根据一个关键字,在主列表中找到一个元素,这个关键字可以是内层列表或元组中的任何一个元素。比如:
使用上面的列表:
find(student_tuples, 'A')
或者
find(student_tuples, 15)
都会返回
('john', 'A', 15)
我在寻找一种高效的方法。
4 个回答
4
你可以使用Python的列表推导式来选择和过滤数据:
def find(tuples, term):
return [tuple for tuple in tuples if term in tuple]
10
如果你只想找到第一个匹配的结果,可以使用下面的代码:
def find(list_of_tuples, value):
return next(x for x in list_of_tuples if value in x)
如果没有找到匹配的记录,这段代码会抛出一个叫做 StopIteration
的错误。为了抛出一个更合适的错误,你可以使用下面的代码:
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")
17
我会使用 filter()
函数或者列表推导式。
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)