如何根据另一个列表保留列表中的元素 [英] how to keep elements of a list based on another list

查看:180
本文介绍了如何根据另一个列表保留列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个看起来像这样的列表:

I have two lists looking like:

list1 = ['a','a','b','b','b','c','d','e','e','g','g']

list2 = ['a','c','z','y']

我想要做的是将list1的所有那些元素都保留在list2中. 结果应该是:

What I want to do is to keep all those elements of list1 that are also in list2. the outcome should be:

outcome= ['a','a','c']

推荐答案

使用in运算符,可以检查元素是否在序列中.

Using in operator, you can check whether an element is in a seqeunce.

>>> list2 = ['a','c','z','y']
>>> 'x' in list2
False
>>> 'y' in list2
True

使用列表理解:

>>> list1 = ['a','a','b','b','b','c','d','e','e','g','g']
>>> list2 = ['a','c','z','y']
>>> [x for x in list1 if x in list2]
['a', 'a', 'c']

但是x in list效率不高.最好将list2转换为 set 对象.

But x in list is not efficient. You'd better convert list2 to a set object.

>>> set2 = set(list2)
>>> [x for x in list1 if x in set2]
['a', 'a', 'c']

这篇关于如何根据另一个列表保留列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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