Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python集的意外行为。\u包含___Python_List_Set - Fatal编程技术网

python集的意外行为。\u包含__

python集的意外行为。\u包含__,python,list,set,Python,List,Set,从\uuuu中借用文档包含\uuuuu文档 print set.__contains__.__doc__ x.__contains__(y) <==> y in x. 那么这是一个bug还是一个特性呢?aset对其元素进行哈希运算,以允许快速查找。您必须覆盖\uuuuu散列\uuuuu方法,以便可以找到元素: class CA(object): def __hash__(self): return hash(self.name) 列表不使用散列,而是像循环中的那样比较

\uuuu中借用文档包含\uuuuu
文档

print set.__contains__.__doc__
x.__contains__(y) <==> y in x.
那么这是一个bug还是一个特性呢?

a
set
对其元素进行哈希运算,以允许快速查找。您必须覆盖
\uuuuu散列\uuuuu
方法,以便可以找到元素:

class CA(object):
  def __hash__(self):
    return hash(self.name)

列表不使用散列,而是像循环中的
那样比较每个元素。

这是因为
CA
没有实现

明智的实施办法是:

def __hash__(self):
    return hash(self.name)

对于
set
s和
dicts
,您需要定义。任何两个相等的对象都应该散列相同的值,以便在
set
s和
dicts
中获得一致/预期的行为

我会使用一个
\u键
方法进行返回,然后在需要比较项目部分的任何地方引用该键,就像您从
\uuuu ne\uuuu
调用
\uu eq
一样,而不是重新实现它:

class CA(object):
  def __init__(self,name):
    self.name = name

  def _key(self):
    return type(self), self.name

  def __hash__(self):
    return hash(self._key())

  def __eq__(self,other):
    if self._key() == other._key():
      return True
    return False

  def __ne__(self,other):
    return not self.__eq__(other)

这个问题应该在stackoverflow展示:如何提问。用一个小例子来说明这个问题。正如其他人在这里回答的那样,集合使用散列值,否则它们将获得列表的性能..样式说明:使用
返回self.name==other.name
而不是
,如果cond:return True\n return False
class CA(object):
  def __init__(self,name):
    self.name = name

  def _key(self):
    return type(self), self.name

  def __hash__(self):
    return hash(self._key())

  def __eq__(self,other):
    if self._key() == other._key():
      return True
    return False

  def __ne__(self,other):
    return not self.__eq__(other)