Python:使用另一个列表过滤列表 [英] Python: filter list of list with another list

查看:79
本文介绍了Python:使用另一个列表过滤列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试过滤列表,我想从列表A(是列表的列表)中提取与之匹配的元素,它们的键索引为0,而另一个列表B则具有一系列的值

i'm trying to filter a list, i want to extract from a list A (is a list of lists), the elements what matches they key index 0, with another list B what has a serie of values

像这样

list_a = list(
  list(1, ...),
  list(5, ...),
  list(8, ...),
  list(14, ...)
)

list_b = list(5, 8)

return filter(lambda list_a: list_a[0] in list_b, list_a)

应返回:

list(
    list(5, ...),
    list(8, ...)
)

我该怎么做?谢谢!

推荐答案

使用列表理解:

result = [x for x in list_a if x[0] in list_b]

为了提高性能,请先将list_b转换为set.

For improved performance convert list_b to a set first.

正如@kevin在评论中指出的,类似list(5,8)的东西(除非它不是伪代码)无效,并且您会收到错误消息.

As @kevin noted in comments something like list(5,8)(unless it's not a pseudo-code) is invalid and you'll get an error.

list()仅接受一项,并且该项目应该是可迭代的/迭代器

list() accepts only one item and that item should be iterable/iterator

这篇关于Python:使用另一个列表过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆