回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>根据我对Python 2.7.2文档<a href="http://docs.python.org/library/stdtypes.html#set-types-set-frozenset" rel="nofollow noreferrer">Built-In Types 5.7 Set Types</a>的解释,应该可以通过将A传递给<code>set.remove(elem)</code>或<code>set.discard(elem)</code>来从集合B中删除集合A的元素</p>
<p>从2.7.2的文档中:</p>
<blockquote>
<p>Note, the elem argument to the <code>__contains__()</code>, <code>remove()</code>, and <code>discard()</code>
methods may be a set.</p>
</blockquote>
<p>我将其解释为我可以将<code>set</code>传递给<code>remove(elem)</code>或<code>discard(elem)</code>,并且所有这些元素都将从目标集中移除。我会用这个来做一些奇怪的事情,比如从字符串或<a href="https://stackoverflow.com/questions/5951961/how-can-i-remove-all-instances-of-a-single-set-item-in-set-a-from-set-b">remove all common words from a word-frequency histogram</a>中删除所有元音。下面是测试代码:</p>
<pre><code>Python 2.7.2 (default, Jun 12 2011, 14:24:46) [M...
Type "help", "copyright", "credits" or "license"
>>> a = set(range(10))
>>> b = set(range(5,10))
>>> a
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b
set([8, 9, 5, 6, 7])
>>> a.remove(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: set([8, 9, 5, 6, 7])
>>> a.discard(b)
>>> a
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>
</code></pre>
<p>我希望它能回来:</p>
<pre><code>>>> a
set([0, 1, 2, 3, 4])
</code></pre>
<p>我知道我可以通过返回一个新集合的<code>a.difference(b)</code>;或者使用<code>set.difference_update(other)</code>;或者使用修改集合的集合运算符<code>a -= b</code>。</p>
<p>那么这是文档中的一个bug吗?<code>set.remove(elem)</code>是否可以不将集合作为参数?或者文档是指集合的集合吗?鉴于<code>difference_update</code>完成了我的解释,我想情况是后者。</p>
<p>这还不够清楚吗?</p>
<p><strong>编辑</strong>
经过3年额外的(一些专业的)python工作,最近又回到了这个问题上,我意识到现在我真正想要做的事情可以通过以下方法来完成:</p>
<pre><code>>>> c = a.difference(b)
set([0,1,2,3,4])
</code></pre>
<p>这就是我最初想要得到的。</p>
<p><strong>编辑</strong>
经过4年多的python开发。。。我意识到使用set literals和<code>-</code>运算符可以更清楚地表示这个操作;而且更完整地说明了set difference是非交换的。</p>
<pre><code>>>> a={0,1,2,3}
>>> b={2,3,4,5}
>>> a-b
set([0, 1])
>>> b-a
set([4, 5])
</code></pre>