[英]Example of set subtraction in python
I'm taking a data structures course in Python, and a suggestion for a solution includes this code which I don't understand.我正在学习 Python 中的数据结构课程,解决方案的建议包括我不理解的这段代码。
This is a sample of a dictionary:这是字典的示例:
vc_metro = {
'Richmond-Brighouse': set(['Lansdowne']),
'Lansdowne': set(['Richmond-Brighouse', 'Aberdeen'])
}
It is suggested that to remove some of the elements in the value, we use this code:建议删除值中的一些元素,我们使用以下代码:
vc_metro['Lansdowne'] -= set(['Richmond-Brighouse'])
I have never seen such a structure, and using it in a basic situation such as:我从未见过这样的结构,并在基本情况下使用它,例如:
my_list = [1, 2, 3, 4, 5, 6]
other_list = [1, 2]
my_list -= other_list
doesn't work.不起作用。 Where can I learn more about this recommended strategy?
我在哪里可以了解有关此推荐策略的更多信息?
You can't subtract lists, but you can subtract set
objects meaningfully.您不能减去列表,但可以有意义地减去
set
对象。 Sets are hashtables, somewhat similar todict.keys()
, which allow only one instance of an object. 集合是哈希表,有点类似于
dict.keys()
,它只允许一个对象的一个实例。
The -=
operator is equivalent to the difference
method, except that it is in-place. -=
运算符等同于difference
方法,只是它是就地的。 It removes all the elements that are present in both operands from the left one.它从左侧删除两个操作数中存在的所有元素。
Your simple example with sets would look like this:您带有集合的简单示例如下所示:
>>> my_set = {1, 2, 3, 4, 5, 6}
>>> other_set = {1, 2}
>>> my_set -= other_set
>>> my_set
{3, 4, 5, 6}
Curly braces with commas but no colons are interpreted as a set object.带逗号但没有冒号的花括号被解释为一个集合对象。 So the direct constructor call
所以直接构造函数调用
set(['Richmond-Brighouse'])
is equivalent to相当于
{'Richmond-Brighouse'}
Notice that you can't do set('Richmond-Brighouse')
: that would add all the individual characters of the string to the set, since strings are iterable.请注意,您不能执行
set('Richmond-Brighouse')
:这会将字符串的所有单个字符添加到集合中,因为字符串是可迭代的。
The reason to use -=
/ difference
instead of remove
is that differencing only removes existing elements, and silently ignores others.使用
-=
/ difference
而不是remove
是差异仅删除现有元素,而默默地忽略其他元素。 The discard
method does this for a single element. discard
方法为单个元素执行此操作。 Differencing allows removing multiple elements at once.差分允许一次删除多个元素。
The original line vc_metro['Lansdowne'] -= set(['Richmond-Brighouse'])
could be rewritten as原始行
vc_metro['Lansdowne'] -= set(['Richmond-Brighouse'])
可以重写为
vc_metro['Lansdowne'].discard('Richmond-Brighouse')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.