Python列表理解:for和if语句?
1]正确的输出 如果Python列表理解:for和if语句?,python,if-statement,list-comprehension,Python,If Statement,List Comprehension,1]正确的输出 如果 fruits = ["apple", "banana", "cherry", "kiwi", "mango"] 2]错误即使for在if之前,如上所述 newlist1 = [x for x in fruits if "a" in x] ^^^ ^^ 3]纠正输出 但是这里if和else在for之前
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
2]错误即使for在if之前,如上所述
newlist1 = [x for x in fruits if "a" in x]
^^^ ^^
3]纠正输出
但是这里if和else在for之前
newlist2 = [x for x in range(10) if x != 5 else 6]
^^^ ^^ ^^^^
我可以知道为什么语句3呈现输出,而语句2抛出错误吗?在第二个示例中
if x!=5 else 6
不是返回true或false的筛选条件。这是一个不完整的语句if-else
,没有定义。
没有“其他”部分,它是一个过滤器。(例1)
在第三个示例中,如果x!=5其他6。
但是它返回x的值,并且不过滤任何内容。您混合了
if
的三种不同用法。1.作为理解语法的一部分正确使用。2.理解中的语句语法3。作为理解中的三元运算符。
newlist3 = [x if x != 5 else 6 for x in range(10)]
^^ ^^^^ ^^^