假设我有一个列表列表或元组列表,无论哪个都可以更有效地解决我的问题.例如:
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
Run Code Online (Sandbox Code Playgroud)
任务是基于作为内部列表或元组的任何元素的键在主列表中查找元素.例如:
使用上面的列表:
find(student_tuples, 'A')
Run Code Online (Sandbox Code Playgroud)
要么
find(student_tuples, 15)
Run Code Online (Sandbox Code Playgroud)
都会回来的
('john', 'A', 15)
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种有效的方法.
Dae*_*yth 14
我会使用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)
Run Code Online (Sandbox Code Playgroud)
要仅查找第一个匹配项,您可以使用
def find(list_of_tuples, value):
return next(x for x in list_of_tuples if value in x)
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15997 次 |
| 最近记录: |