<p>我认为两个嵌套循环的逻辑是根本错误的。目前的工作原理如下:</p>
<pre><code>for x in first_iterable:
for y in second_iterable:
if x != y:
do_something(x)
</code></pre>
<p>试着用几个<code>range</code>作为你的iterables,我想你会发现它并没有达到你想要的效果。<code>do_something(x)</code>调用将在<code>x</code>和<code>y</code>值不匹配的每一次</em>发生<em>,每个<code>x</code>可能发生很多次</p>
<p>对于您的用例,您只希望它每<code>x</code>运行一次,并且仅当它从不匹配<code>y</code>时。为此,您可能需要更像这样的代码:</p>
<pre><code>for x in first_iterable:
if x not in second_iterable:
do_something(x)
</code></pre>
<p>编写<code>not in</code>测试的另一种方法是使用<code>all(x != y for y in second_iterable)</code>(这对于比简单不等式更复杂的测试更方便)。此代码将在运行<code>do_something(x)</code>之前检查<code>second_iterable</code>中的所有<em>值,而不是在有许多不匹配对的情况下重复执行</p>
<p>将其放在当前代码中(将冗余的标题相关变量删减为一个,并给它一个更好的名称):</p>
<pre><code>for submission in source.new(limit=50):
crosspost_title = submission.title + " (by X)"
if all(crosspost_title != other.title for other in subreddit.new(limit=200)):
...
</code></pre>
<p>请注意,如果将关键字检查(例如<code>"string1"</code>)移到检查文章是否已交叉发布之前,可能会提高代码的效率。我建议对该测试使用<code>any</code>,而不是使用一大堆代码相同的<code>if</code>测试(<code>if any(keyword in title for keyword in ["string1", "string2", ...]):</code>)</p>