查找不在列表中的元素 [英] Finding elements not in a list

查看:58
本文介绍了查找不在列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我的代码:

item = [0,1,2,3,4,5,6,7,8,9]
z = []  # list of integers

for item in z:
    if item not in z:
        print item

z包含一个整数列表.我想将itemz进行比较,并打印出与item相比不在z中的数字.

z contains a list of integers. I want to compare item to z and print out the numbers that are not in z when compared to item.

我可以打印出z中的元素,而不是item,但是当我尝试使用上面的代码执行相反的操作时,

I can print the elements that are in z when compared not item, but when I try and do the opposite using the code above nothing prints.

有帮助吗?

推荐答案

您的代码没有执行我认为您认为正在执行的操作.行for item in z:将遍历z,每次使item等于z的一个元素.因此,原始的item列表会在您执行任何操作之前被覆盖.

Your code is not doing what I think you think it is doing. The line for item in z: will iterate through z, each time making item equal to one single element of z. The original item list is therefore overwritten before you've done anything with it.

我认为您想要这样的东西:

I think you want something like this:

item = [0,1,2,3,4,5,6,7,8,9]

for element in item:
    if element not in z:
        print element

但是您可以轻松地这样做:

But you could easily do this like:

[x for x in item if x not in z]

或(如果您不介意丢失非唯一元素的重复项):

or (if you don't mind losing duplicates of non-unique elements):

set(item) - set(z)

这篇关于查找不在列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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