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

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

问题描述

我有两个列表:

list1 = ['a','a','b','b','b','c','d','e','e','g','G']list2 = ['a','c','z','y']

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

结果= ['a','a','c']

解决方案

使用 in 操作符,可以检查一个元素是否在一个序列中.

<预><代码>>>>list2 = ['a','c','z','y']>>>列表 2 中的x"错误的>>>列表 2 中的y"真的

使用列表推导:

<预><代码>>>>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 对象.

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

I have two lists looking like:

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

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

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']

解决方案

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

Using list comprehension:

>>> 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']

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