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) 

更多相关文章

  1. 对numpy数组的每n个元素求平均值
  2. 008 Python基本语法元素小结
  3. 如何将两个列表中的数据写入csv中的列?
  4. 在python 3.3列表中查找最小值
  5. python基础练习--列表问题
  6. 如何用所有可能的方式将一个列表分割成对?
  7. 学习python的第十六天(迭代器,三元表达式,列表生成式,字典生成式,
  8. Ansible:维护sudoers列表的最佳实践
  9. Python根据第一项从2d数组中删除元素

随机推荐

  1. Android: Android NDK Overview
  2. Android 内存泄漏场景分析
  3. Android android:persistentDrawingCache
  4. Android 短信发送器
  5. Android7.0中文文档(API)-- ShareActionPro
  6. AndroidStudio使用教程(第一弹)
  7. Cocos2d-x C++调用Android弹出提示框
  8. Android 麦克风录音动画
  9. json解析android客户端源码
  10. 不错的Android开发资料,收藏一下