문제

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))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top