<p>在Python中,可以在列表理解中使用<strong>表达式,但不能使用<strong>语句。您可能想看看Python中的<a href="https://stackoverflow.com/questions/4728073/what-is-the-difference-between-an-expression-and-a-statement-in-python">diffence between expressions and statements</a>。你知道吗</p>
<p>至于你在如何计算<code>((# of matching nodes) * (1 if the relationship doesn't match, 2.5 if it does))</code>的评论中的问题,这是你问题中论文的^{<SABK</strong>相似函数的分子,你可以使用生成器和<code>sum</code>函数来完成:</p>
<pre><code>theta = 2.5
sim = sum((((d1[0] == d2[0]) + (d1[2] == d2[2])) * (theta if d1[1] == d2[1] else 1) for d1, d2 in product(deps1, deps2)))
</code></pre>
<p>或者,如果您希望根据每个句子的相似性功能分离代码,从而提高代码的可读性:</p>
<pre><code>def sim_per_sentence(d1, d2):
matching_nodes = (d1[0] == d2[0]) + (d2[0] == d2[0])
relation_sim = theta if d1[1] == d2[1] else 1
return matching_nodes * relation_sim
sim = sum((sim_per_sentence(d1, d2) for d1, d2 in product(deps1, deps2)))
</code></pre>
<p>请注意,如果在<code>deps1</code>和<code>deps2</code>中有许多元素,那么使用<a href="https://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension">generator expression instead of a list comprehension</a>可能更有效,因为每个迭代的单个结果不需要存储在内存中。你知道吗</p>