Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.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类列表,索引()不工作_Python - Fatal编程技术网

Python类列表,索引()不工作

Python类列表,索引()不工作,python,Python,不知道我做错了什么。我有这门课: class Node: ''' Class to contain the lspid seq and all data. ''' def __init__(self, name,pseudonode,fragment,seq_no,data): self.name = name self.data = {} self.pseudonode = pseudonode s

不知道我做错了什么。我有这门课:

class Node:
    '''
    Class to contain the lspid seq and all data.
    '''
    def __init__(self, name,pseudonode,fragment,seq_no,data):
        self.name = name
        self.data = {}
        self.pseudonode = pseudonode
        self.seq_no = seq_no
        self.fragment = fragment
    def __unicode__(self):
        full_name = ('%s-%d-%d') %(self.name,self.pseudonode,self.fragment)
        return str(full_name)
    def __cmp__(self, other):
        if self.name > other.name:
            return 1
        elif self.name < other.name:
            return -1
        return 0
    def __repr__(self):
        full_name = ('%s-%d-%d') %(self.name,self.pseudonode,self.fragment)
        #print 'iside Node full_name: {} \n\n\n ------'.format(full_name)
        return str(full_name)
我正在尝试获取列表节点[]中某个节点的索引

>>> node
0000.0000.0001-1-0
>>> nodes.index(node) 
0
0不是我所期望的。不知道为什么会这样

编辑
我正在获取列表的索引,其中“0000.0000.0001-1-0”为

在容器上使用
index
函数时,依赖其元素的
\uuu cmp\uu
函数返回其认为等于输入对象的第一个元素的索引。您可能也知道很多,因为您为节点实现了它。但是您所期望的是,
\uu\cmp\uu
不仅考虑名称,还考虑伪节点和片段,对吗

一种直截了当的方法是将它们看作元组,它执行从左到右的元素比较,直到发现第一个不等式:

def __cmp__(self, other):
    self_tuple = (self.name, self.pseudonode, self.fragment)
    other_tuple = (other.name, other.pseudonode, other.fragment)
    if self_tuple > other_tuple:
        return 1
    elif self_tuple < other_tuple:
        return -1
    return 0
def\uuuu cmp\uuuu(自身、其他):
self_tuple=(self.name、self.pseudonode、self.fragment)
other_tuple=(other.name、other.pseudonode、other.fragment)
如果自组>其他组:
返回1
elif自组<其他组:
返回-1
返回0

如果您想要另一个顺序,可以使用元组顺序来定义它。

这就是您定义相等的方式。“不是我所期望的”-那么您期望的是什么?为什么呢?我希望列表的索引“0000.0000.0001-1-0”应该是1。谢谢你的例子和解释。
def __cmp__(self, other):
    self_tuple = (self.name, self.pseudonode, self.fragment)
    other_tuple = (other.name, other.pseudonode, other.fragment)
    if self_tuple > other_tuple:
        return 1
    elif self_tuple < other_tuple:
        return -1
    return 0