本文介绍了Python 列表理解和“不在"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

问题:是否可以使用列表理解来创建 t 中的元素列表,而 s 中没有?>

我尝试了以下操作,但出现错误:

>>>t = [1, 2, 3, 4, 5]>>>s = [1, 3, 5]>>>[t 表示 t 不在 s][t 代表 t 不在 s]^语法错误:无效语法
解决方案

试试这个:

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

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

my_list = [(x,a)对于 x 在 t如果 x 不在 s如果 x >0对于一个在 y...]

看到了吗?

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

Question: Is it possible to use list comprehension to create a list of elements in t that is not found in 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
解决方案

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.

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

See?

这篇关于Python 列表理解和“不在"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:44