使用python如何根据作为内部列表元素的键在列表列表中查找元素?
假设我有一个列表或元组列表,哪一个能更有效地解决我的问题。例如:使用python如何根据作为内部列表元素的键在列表列表中查找元素?
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
任务是根据内部列表或元组的任何元素的键在主列表中查找元素。例如:
使用上面的列表:
find(student_tuples, 'A')
或
find(student_tuples, 15)
就都返回
('john', 'A', 15)
我在寻找一种有效的方法。
我会用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)
您可以通过将返回值更改为:return [学生在学生中的学生,如果学生的价值]来改善。否则,它只会返回元组中第二个和第三个值的命中。 – 2011-04-13 17:23:03
@bigmattyh:如果value =='john'',那会返回'('john'...)',这不是OP想要的。 – Daenyth 2011-04-13 17:25:55
他说:“任务是根据一个键是内部列表或元组**的任何元素在主列表中找到一个元素。” – 2011-04-13 17:30:04
要只找到了第一场比赛,你可以使用
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")
该函数将返回包含搜索项的元组列表。在这里你去:
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)]
您可以使用Python的列表理解来选择和过滤:
def find(tuples, term):
return [tuple for tuple in tuples if term in tuple]
你应该考虑制定'Student'类,并让您的学生的名单包含的类的实例。 – Daenyth 2011-04-13 17:13:16