Python:用另一个列表过滤列表列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18448469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:47:16  来源:igfitidea点击:

Python: filter list of list with another list

pythonlistfilter

提问by fj123x

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

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

like this

像这样

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)

should return:

应该返回:

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

How can i do this? Thanks!

我怎样才能做到这一点?谢谢!

回答by Ashwini Chaudhary

Use a list comprehension:

使用列表理解:

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

For improved performance convert list_bto a set first.

为了提高性能list_b,请先转换为一组。

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.

正如@kevin 在评论中指出的那样list(5,8)(除非它不是伪代码)是无效的,你会得到一个错误。

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

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

回答by Ashwini Chaudhary

You are actually very close. Just do this:

你实际上非常接近。只需这样做:

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

# Fix the syntax here
list_b = [5, 8]

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