[英]Python lambda with any()
I have a list of words in a list self.terms
, and a string line
. 我在self.terms
列表中有一个单词列表,还有一个字符串line
。 If any of the terms in the list are in line
, I'd like to write them out to a file terms_file
. 如果列表中的任何术语line
,我想将它们写到文件terms_file
。
I used any()
as shown below, but this returns a boolean. 我使用了any()
,如下所示,但这返回一个布尔值。
any(terms_file.write(term) for term in self.terms if term in line)
How can I write out to the file? 如何写出文件? I tried adding a lambda but I'm not really familiar with them and that did not work. 我尝试添加一个lambda,但是我对它们并不真正熟悉,因此无法正常工作。 I got some syntax errors, but after some changes, I got False
returned again. 我遇到了一些语法错误,但是经过一些更改后,我又返回了False
。
Is it possible to do this using any()
? 是否可以使用any()
做到这一点?
Don't use any()
here; 不要在这里使用any()
; you don't even use the return value. 您甚至都不使用返回值。
To write all matching terms, use: 要编写所有匹配的术语,请使用:
terms_file.write(''.join(term for term in self.terms if term in line))
but it'd be better to just use a regular loop; 但是最好使用常规循环; readability counts! 可读性很重要!
for term in self.terms:
if term in line:
terms_file.write(term)
Use any()
only if you want to know about the boolean result of the test; 仅当您想了解测试的布尔结果时才使用any()
。 any()
stops iterating when it finds the first True
value. 当找到第一个True
值时, any()
停止迭代。 In your case terms_file.write()
returns None
, so it'll never even encounter True
and always return False
. 在您的情况下, terms_file.write()
返回None
,因此它将永远不会遇到True
并始终返回False
。
any
will tell you whether any of the terms where present in line
(hence the name). any
会告诉您是否有任何术语出现line
(因此而得名)。
You can just create a list of those terms: 您可以只创建这些术语的列表:
present_terms = list(terms_file.write(term) for term in self.terms if term in line)
and write that to a file, possibly after joining the list items: 并将其写入文件(可能在加入列表项之后):
out_file.write(' '.join(present_terms))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.