基于Python中的其他列表,列表理解的过滤嵌套列表
我有两个这样的列表:
a = [[1,2,3],[2,3,4],[5,6,7],[7,8,9]]
b = [1,2]
我现在想过滤列表a,以保留列表b中包含项目的项目。因此,所需的输出看起来像这样:
[[1,2,3],[2,3,4]]
我尝试了一些嵌套的列表综合,我可以想到,但无法获得所需的输出。任何建议将不胜感激。
I have two lists like this:
a = [[1,2,3],[2,3,4],[5,6,7],[7,8,9]]
b = [1,2]
I would now like to filter list a, to keep only the items which contain the items in list b. So the desired output would look like this:
[[1,2,3],[2,3,4]]
I have tried some nested list comprehensions, which I could think of, but could not get the desired output. Any advice is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以尝试这样的事情:
you could try something like this :
我会尝试这样的事情:
I would try something like this:
列表理解和集合的结合将产生所需的结果。笔记;我认为,如果情况是这样,重复的项目和订购就不感兴趣 - 一组将无法正常工作,因为它忽略了排序,并且只允许唯一的项目。
一个简单的列表理解将会做到,就像下面的
主要是此列表理解的一个有趣的部分,即
(如果未设置)(sublist).isdisjoint(filter_items)
。在这里,只有当sublist的集合不是 dissem_items ie ie ie ie ie ie ie ie ie ie ie ie ie ie ie ie n none none none,才能保留sublist。 filter_items的属于sublist。对于您给定的示例,提供的答案将产生以下内容:
A combination of list comprehension and sets would yield the wanted result. Note; I assume that repeated items and ordering is not of interest, if this is the case - a set won't work since it ignores ordering and only allows unique items.
A simple list comprehension would do, like below
There's mainly one interesting part of this list comprehension, namely the
if not set(sublist).isdisjoint(filter_items)
. Here you only keep the sublist if the set of sublist is not disjoint of the set filter_items i.e. none of the filter_items is in the sublist.for your given example the provided answer would yield the following:
使用
set
方法中的可以模仿相交:
Using a
set
approach thein
can be mimic with an intersection:我会尝试这样的事情。
I would try something like this.