擅长:python、mysql、java
<p>您面临的主要问题是,您将在第一次迭代中返回。<code>return</code>将结束函数的执行。你知道吗</p>
<p>如果要检查是否所有行都包含“?”,则检查应该是在未找到“?”时返回的内容。如果您设法耗尽您的迭代,那么所有的行都有'?'你只需返回真值。你知道吗</p>
<pre><code>def char_finder(filename):
with open(filename, "r") as inputFile:
for line in inputFile:
if '?' not in line:
return False
return True
</code></pre>
<p>此外,请注意,文件的读取现在使用的是上下文管理器,这在这里是一种更干净的方法。你知道吗</p>
<p>最后,要完全重构它,我们可以使用<a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow noreferrer">all</a>函数,它将遍历每一行,一旦发现不匹配的条件,它就会短路。这几乎就是上面显示的,但所有的工作都是为我们做的:</p>
<pre><code>def char_finder(filename):
with open(filename, "r") as inputFile:
return all('?' in line for line in inputFile)
</code></pre>