简体   繁体   中英

Python lambda with any()

I have a list of words in a list self.terms , and a string line . If any of the terms in the list are in line , I'd like to write them out to a file terms_file .

I used any() as shown below, but this returns a boolean.

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. I got some syntax errors, but after some changes, I got False returned again.

Is it possible to do this using any() ?

Don't use any() here; 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() stops iterating when it finds the first True value. In your case terms_file.write() returns None , so it'll never even encounter True and always return False .

any will tell you whether any of the terms where present in line (hence the name).

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM