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

查看:22
本文介绍了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 转换为集合.

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天全站免登陆