<p>合适的信用证是</p>
<pre><code>[entry for tag in tags for entry in entries if tag in entry]
</code></pre>
<p>LC中循环的顺序与嵌套循环的顺序类似,if语句在末尾,条件表达式在开头,类似于</p>
<pre><code>[a if a else b for a in sequence]
</code></pre>
<p>看演示-</p>
<pre><code>>>> tags = [u'man', u'you', u'are', u'awesome']
>>> entries = [[u'man', u'thats'],[ u'right',u'awesome']]
>>> [entry for tag in tags for entry in entries if tag in entry]
[[u'man', u'thats'], [u'right', u'awesome']]
>>> result = []
for tag in tags:
for entry in entries:
if tag in entry:
result.append(entry)
>>> result
[[u'man', u'thats'], [u'right', u'awesome']]
</code></pre>
<p><strong>编辑</strong>-由于需要将结果展平,因此可以使用类似的列表理解,然后展平结果。</p>
<pre><code>>>> result = [entry for tag in tags for entry in entries if tag in entry]
>>> from itertools import chain
>>> list(chain.from_iterable(result))
[u'man', u'thats', u'right', u'awesome']
</code></pre>
<p>把这些加在一起,你就可以</p>
<pre><code>>>> list(chain.from_iterable(entry for tag in tags for entry in entries if tag in entry))
[u'man', u'thats', u'right', u'awesome']
</code></pre>
<p>这里使用生成器表达式而不是列表理解。(也完全匹配79个字符的限制(没有<code>list</code>调用)</p>