擅长:python、mysql、java
<p>使用<a href="https://stackoverflow.com/questions/6331497/an-elegant-way-to-get-hashtags-out-of-a-string-in-python/6331563#6331563">@inspectorG4dget's answer</a>时,如果不需要重复项,可以使用集合理解而不是列表理解。</p>
<pre><code>>>> tags="Hey guys! #stackoverflow really #rocks #rocks #announcement"
>>> {tag.strip("#") for tag in tags.split() if tag.startswith("#")}
set(['announcement', 'rocks', 'stackoverflow'])
</code></pre>
<p>请注意,集合理解的<code>{ }</code>语法仅从Python 2.7开始工作。<br/>
如果使用的是旧版本,则将列表理解(<code>[ ]</code>)输出作为<code>set</code>函数。</p>