Python 使用 if 语句进行列表理解
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15474933/
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
List comprehension with if statement
提问by OrangeTux
I want to compare 2 iterables and print the items which appear in both iterables.
我想比较 2 个迭代并打印出现在两个迭代中的项目。
>>> a = ('q', 'r')
>>> b = ('q')
# Iterate over a. If y not in b, print y.
# I want to see ['r'] printed.
>>> print([ y if y not in b for y in a])
^
But it gives me a invalid syntax error where the ^has been placed.
What is wrong about this lamba function?
但它给了我一个无效的语法错误^。这个lamba函数有什么问题?
采纳答案by Volatility
You got the order wrong. The ifshould be after the for(unless it is in an if-elseternary operator)
你顺序错了 在if应后的for(除非它是在if-else三元运算符)
[y for y in a if y not in b]
This would work however:
但是,这会起作用:
[y if y not in b else other_value for y in a]
回答by eumiro
This is not a lambda function. It is a list comprehension.
这不是 lambda 函数。这是一个列表理解。
Just change the order:
只需更改顺序:
[ y for y in a if y not in b]
回答by Martijn Pieters
You put the ifat the end:
你把 放在if最后:
[y for y in a if y not in b]
List comprehensions are written in the same order as their nested full-specified counterparts, essentially the above statement translates to:
列表推导式的编写顺序与其嵌套的完整指定对应项相同,基本上上述语句转换为:
outputlist = []
for y in a:
if y not in b:
outputlist.append(y)
Your version tried to do this instead:
您的版本尝试这样做:
outputlist = []
if y not in b:
for y in a:
outputlist.append(y)
but a list comprehension muststart with at least oneouter loop.
但是列表推导式必须以至少一个外循环开始。
回答by Vishvajit Pathak
list comprehension formula:
列表理解公式:
[<value_when_condition_true> if <condition> else <value_when_condition_false> for value in list_name]
thus you can do it like this:
因此你可以这样做:
[y for y in a if y not in b]
Only for demonstration purpose : [y if y not in b else False for y in a ]
仅用于演示目的:[y if y not in b else False for y in a ]
回答by Deepak Dhiman
I researched and tried above mentioned suggestions of list comprehension for my situation as described below however it didn't work. What am i doing wrong here?
我研究并尝试了上面提到的针对我的情况的列表理解建议,如下所述,但它没有用。我在这里做错了什么?
sent_splt=[['good', 'case,', 'excellent', 'value.'], ['great', 'for', 'the', 'jawbone.'],['tied', 'to', 'charger', 'for', 'conversations', 'lasting', 'more', 'than', '45', 'minutes.major', 'problems!!']]
stop_set = ['the', 'a', 'an', 'i', 'he', 'she', 'they', 'to', 'of', 'it', 'from']
x=[a for a in sent_splt if a not in stop_set]
print(x)
It is not filtering the words.
它不是过滤单词。

