【问题标题】:access a list with indices that are list访问具有列表索引的列表
【发布时间】:2016-09-16 05:26:44
【问题描述】:

我的 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 超类中创建的坐标列表? 是否有可能使用另一个列表对列表进行索引?

【问题讨论】:

  • 可能不相关,但 p[0,0], p[0,1] == (1,1) 评估为 p[0,0], (p[0,1] == (1,1))
  • 有可能是这样的:a = [1,1] assert a[0], a[1] == (1,1)
  • a[0], a[1] == (1,1) 将评估为(1, False)。你可能想要assert (a[0], a[1] == (1,1))。相关:stackoverflow.com/q/37313471/1639625
  • 你是对的!我没有打印答案来看看我得到了什么
  • p[1, 0] 之类的会是什么?这似乎并不明显,我很好奇。

标签: python


【解决方案1】:

如果我对您的理解正确,您想从另一个列表中的列表访问一个元素。

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

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

print(nested_list[1][0])

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

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

【讨论】:

  • 我很容易用 p[0], p[1] == (1,1) 断言我的 Point 实例。是真的。但我必须明确遵守练习规则。问题是这对坐标是一个像这样的列表 p._coords = [1,1]。所以我不知道如何实现 p[0,0] 以便访问可以轻松访问的内容 p[0]
【解决方案2】:

如果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'

这种方法可以让您匹配断言语法。

【讨论】:

  • 谢谢。我会试着把我的列表变成字典
猜你喜欢
  • 2012-02-18
  • 2018-05-15
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
相关资源
最近更新 更多