访问索引为lis的列表

2024-03-29 15:56:53 发布

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

我被分配了一个python课程的练习。目标是创建一些几何对象作为Shape对象的子类,这些子类将通过断言评估。你知道吗

代码如下:

class Shape(object):
    __metaclass__ = ABCMeta
    def __init__(self, coords):
        super(Shape, self).__init__()
        self._coords = list(map(int, coords))

    def __getitem__(self, key):
        return self._coords[key]

    def move(self, distance):
        self._coords = distance

class Point(Shape):
    def __init__(self, coords):
        super(Point,self).__init__(coords)

if __name__ == '__main__':
    p = Point((0,0))
    p.move((1,1))
    assert p[0,0], p[0,1] == (1,1) # Check the coordinates

问题是如何访问在具有列表索引的Shape超类中创建的坐标列表? 一个列表是否有可能使用另一个列表编制索引?你知道吗


Tags: 对象keyself列表moveinitdefcoords
2条回答

如果我理解正确,那么您希望从另一个列表中的列表访问元素。你知道吗

为此,只需将每个索引写在一对单独的方括号中。你知道吗

如果您的列表是nested_list = [ [1, 2] , [3, 4] ],那么您可以这样访问4项:

print(nested_list[1][0])

这等于下面的长格式,它应该阐明链接索引查找的工作原理:

inner_list = nested_list[1]
print(inner_list[0])

如果objdict,那么obj[m,n]==v的确切语法是可能的!你知道吗

任何hashable(最不可变)类型都可以用作字典键。元组,如(1,2),是可散列的。因此,实例化字典是有效的:

>>> my_dict = { (1,2):'A', (6,7,8):'B' }

可以编制索引:

>>> my_dict[1,2]
'A'
>>> my_dict[6,7,8]
'B'
>>> assert my_dict[6,7,8] == 'B'

这种方法允许您匹配断言语法。你知道吗

相关问题 更多 >