【发布时间】:2017-04-19 20:23:47
【问题描述】:
我在去年夏天使用 K&R 第 2 版学习了 C。从 1989 年开始写 C 的书。然后我决定学习 CS50,现在正在第一次学习 python3。
我还决定在http://www.python-course.eu/python3_sequential_data_types.php 在线学习有关python3 的教程。我在理解深度嵌套列表的 python 索引时遇到了一些麻烦。
我在发帖前搜索了一段时间,但没有看到答案。我在网上找到的例子是这样的:
>>> t = [[100, 'str_1'], [200, 'str_2'], [300, 'str_3']]
我明白。索引与 C 2d char 数组相同。
让我困惑的是:
place= ["High up", ["further down", ["and down", ["deep down", "the answer", 42]]]]
>>> place[0]
'High up'
>>> place[1]
['further down', ['and down', ['deep down', 'the answer', 42]]]
>>> place[1][1]
['and down', ['deep down', 'the answer', 42]]
>>> place[1][1][1]
['deep down', 'the answer', 42]
>>> place[1][1][1][0]
'deep down'
>>> place[1][1][1][0][3]
'p'
我以为我明白了,只要继续看一个,就可以进入下一个列表,但后来我找到了。
>>> complex_list = [["a",["b",["c","x"]]],42]
complex_list[0] #note: index 0 is the entire left, while above it's not.*
['a', ['b', ['c', 'x']]]
>>> complex_list[0][1]
['b', ['c', 'x']]
>>> complex_list[0][1][1][0]
'c'
这两个列表在我看来几乎相同,除了 complex_list 在左侧有两个大括号。 有人可以向我解释一下规则吗,我不明白为什么 place[0] 只是列表中的第一项,而 complex_list[0] 是除了数字 42 之外的整个列表?额外的大括号如何改变索引?
【问题讨论】:
-
我认为
complex_list左边的两个大括号是为了容纳第一个“内部列表”["a",["b",["c","x"]]]和单独的项目42,也许有时你放空格更容易看到在这样的列表项之间:[ ["a",["b",["c","x"]]], 42 ],这就像在说[ [<inner list>], 42],只要大括号匹配(每个左大括号[对应的右大括号])。 -
它不像
C数组那样是几何的。它实际上是指向对象的指针列表。所以每个[]通过另一个指针取消引用。所以下一个[]需要在前一个取消引用的上下文中进行评估。
标签: list python-3.x indexing