Python从s中删除集

2024-04-18 14:51:48 发布

您现在位置:Python中文网/ 问答频道 /正文

根据我对Python 2.7.2文档Built-In Types 5.7 Set Types的解释,应该可以通过将A传递给set.remove(elem)set.discard(elem)来从集合B中删除集合A的元素

从2.7.2的文档中:

Note, the elem argument to the __contains__(), remove(), and discard() methods may be a set.

我将其解释为我可以将set传递给remove(elem)discard(elem),并且所有这些元素都将从目标集中移除。我会用这个来做一些奇怪的事情,比如从字符串或remove all common words from a word-frequency histogram中删除所有元音。下面是测试代码:

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])
>>>

我希望它能回来:

>>> a
set([0, 1, 2, 3, 4])

我知道我可以通过返回一个新集合的a.difference(b);或者使用set.difference_update(other);或者使用修改集合的集合运算符a -= b

那么这是文档中的一个bug吗?set.remove(elem)是否可以不将集合作为参数?或者文档是指集合的集合吗?鉴于difference_update完成了我的解释,我想情况是后者。

这还不够清楚吗?

编辑 经过3年额外的(一些专业的)python工作,最近又回到了这个问题上,我意识到现在我真正想要做的事情可以通过以下方法来完成:

>>> c = a.difference(b)
set([0,1,2,3,4])

这就是我最初想要得到的。

编辑 经过4年多的python开发。。。我意识到使用set literals和-运算符可以更清楚地表示这个操作;而且更完整地说明了set difference是非交换的。

>>> a={0,1,2,3}
>>> b={2,3,4,5}
>>> a-b
set([0, 1])
>>> b-a
set([4, 5])

Tags: the文档元素编辑updaterange运算符事情
3条回答

你已经回答了这个问题。它指集合的集合(实际上包含冻结集合的集合)。

The paragraph you are referring to开始于:

Note, the elem argument to the __contains__(), remove(), and discard() methods may be a set.

这意味着a.remove(b)中的b可以是一个集合,然后继续:

To support searching for an equivalent frozenset, the elem set is temporarily mutated during the search and then restored. During the search, the elem set should not be read or mutated since it does not have a meaningful value.

这意味着,如果b是一个集合,a.remove(b)将扫描a以查找与b等价的冻结集并将其删除(如果不存在,则抛出KeyError)。

在Python中不能有sets的sets,因为set是可变的。相反,您可以使用sets的frozensets。另一方面,您可以使用__contains__()remove()discard()调用set。请参见以下示例:

a = set([frozenset([2])])
set([2]) in a       # you get True
a.remove(set([2]))  # a is now empty

因此,您的问题的答案是文档是指frozensets的sets

我正在查看各种版本的python(用于mac)的内置帮助。这是结果。

  • Python2.5

remove(...)
Remove an element from a set; it must be a member.
If the element is not a member, raise a KeyError.

  • Python2.6

remove(...)
Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError.

  • Python2.7

remove(...)
Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError.

你提到的全部文件实际上都说:

Note, the elem argument to the __contains__(), remove(), and discard() methods may be a set. To support searching for an equivalent frozenset, the elem set is temporarily mutated during the search and then restored.

这似乎是一个脚注,表明参数可能是一个集合,但除非它在集合内找到匹配的冻结集合,否则它不会被删除。关于正在修改的集合的说明是,可以对其进行散列以查找匹配的冻结集合。

相关问题 更多 >