使用python如何在列表列表中找到元素,而关键元素是内部列表的元素?
16lz
2021-01-22
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.
我在寻找一种有效的方法。
4 个解决方案
#1
13
I would use filter()
or a list comprehension.
我将使用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)
更多相关文章
- 对numpy数组的每n个元素求平均值
- 008 Python基本语法元素小结
- 如何将两个列表中的数据写入csv中的列?
- 在python 3.3列表中查找最小值
- python基础练习--列表问题
- 如何用所有可能的方式将一个列表分割成对?
- 学习python的第十六天(迭代器,三元表达式,列表生成式,字典生成式,
- Ansible:维护sudoers列表的最佳实践
- Python根据第一项从2d数组中删除元素