Python 列表理解和“不在”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19507714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:55:42  来源:igfitidea点击:

Python List Comprehension and 'not in'

pythonpython-2.x

提问by Nyxynyx

I'm getting started with Python and is currently learning about list comprehensions so this may sound really strange.

我刚开始使用 Python,目前正在学习列表推导式,所以这听起来可能很奇怪。

Question:Is it possible to use list comprehension to create a list of elements in tthat is not found in s?

问题:是否可以使用列表理解来创建在t中找不到的元素列表s

I tried the following and it gave me an error:

我尝试了以下操作,但它给了我一个错误:

>>> t = [1, 2, 3, 4, 5]
>>> s = [1, 3, 5]
>>>[t for t not in s]

[t for t not in s]
           ^
SyntaxError: invalid syntax

采纳答案by Lucas Ribeiro

Try this:

尝试这个:

[x for x in t if x not in s]

You can nest any for if statements in list comprehensions. Try this identation, to get really long chains of conditionals, with a clearer intuition about what the code is doing.

您可以在列表推导式中嵌套任何 for if 语句。试试这个标识,以获得非常长的条件链,对代码正在做什么有更清晰的直觉。

my_list = [(x,a)
           for x in t
           if x not in s
           if x > 0
           for a in y
           ...]

See?

看?

回答by Leonardo.Z

[item  for item  in t if item not in s]

回答by MangoHands

For better efficiency, use a set:

为了提高效率,请使用一组:

mySet = set(s)
result = [x for x in t if x not in mySet]

Testing membership of a set is done is O(1), but testing membership in a list is O(n).

测试集合的成员资格是 O(1),但测试列表中的成员资格是 O(n)。

回答by Jonathon Reinhart

I know you're asking about list comprehensions, but I wanted to point out that this specificproblem would be better accomplished using sets. The result you want is the difference of set tand s:

我知道您问的是列表推导式,但我想指出,使用s可以更好地完成这个特定问题set。你想要的结果是 sett和的差异s

>>> t = {1,2,3,4,5}
>>> s = {1,3,5}
>>>
>>> t - s
set([2, 4])
>>>
>>> t.difference(s)
set([2, 4])

Just hoping to expand your knowledge of the tools Python provides to you.

只是希望扩展您对 Python 提供给您的工具的了解。