简体   繁体   English

如何比较两个具有不同长度的列表并删除一些元素?

[英]How to compare two lists with different lengths and remove some elements?

I have two lists, the first contains some elements that don't exist in the second list which have more elements. 我有两个列表,第一个包含一些在第二个列表中不存在的元素,这些元素具有更多元素。 I need to delete elements that don't exist in the second list. 我需要删除第二个列表中不存在的元素。

In the example below, I need to delete just the '0' from the first list. 在下面的示例中,我只需要从第一个列表中删除“ 0”即可。 So: 所以:

Input:
list1 = [0,1,2,3]
list2 = [1,2,3,4,5,6,7]

Output:
list1 = [1,2,3]
list2 = [1,2,3,4,5,6,7]

I tried this simple code but it return an empty list 我尝试了这个简单的代码,但它返回了一个空列表

list1=[0,1,2,3]
list2=[1,2,3,4,5,6,7]

for element in list1:
    for element1 in list2:
        if element != element1:
            for element in list1:
                list1.remove(element)
print(list1)

Any help please ? 有什么帮助吗?

You can use sets to do this! 您可以使用集来做到这一点!

set(list1).intersection(list2) # [1,2,3]

You can also use list comprehension but it's slower in theory. 您也可以使用列表推导,但是理论上它比较慢。

list1 = [0,1,2,3]
list2 = [1,2,3,4,5,6,7]

list1 = [x for x in list1 if x in list2] # [1,2,3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM