python - 你能解释为什么这个 Python 元组列表的索引给出 15 作为答案吗?
问题描述
_magnitude_list = [(0,''), (3, 'thousand'), (6, 'million'),
(9, 'billion'), (12, 'trillion'), (15, '')]
index1 = _magnitude_list[-1]
index2 = _magnitude_list[0]
index3 = _magnitude_list[-1][0]
index1 给出 (15, '') 的输出
index2 给出 (0, '') 的输出
index3 给出的输出为 15 而不是 (15, '')(0, '')。为什么会这样?
解决方案
Python 中的负索引(链接)意味着你从列表的末尾开始,所以_magnitude_list[-1]
会给你列表的最后一个元素。
由于您在这里有一个多维结构 - 2 元素元组列表,_magnitude_list[-1]
将为您提供整个最后一个元组,并且_magnitude_list[-1][0]
只为您提供最后一个元组中的第一个元素。
与索引的 0 值类似 - 它会给你列表的第一个元素,在你的情况下_magnitude_list[0]
会给你列表中的整个第一个元组。
推荐阅读
- python - 如何使用 Matplotlib 在 bin 之间的直方图中绘制垂直线?
- c# - 如何在 dotnet core 的块 blob 类型存储中的现有文件中附加新的 csv 数据。我试图附加,但它显示错误
- deep-learning - YOLOv4中的损失和mAP图表
- database - “DocumentSnapshot”类型不是“Map”类型的子类型
' - azure-eventhub - 什么是 bob 容器和检查点
- matlab - 直线和绘图之间的阴影区域
- docker - 我正在尝试在 Ubuntu 20.04.2 LTS 上使用 docker 运行球童服务器,但球童没有启动
- javascript - 使用 JS 更改文本内容
- haskell - 使用 QuickCheck monadicIO 时如何防止测试的函数输出到终端
- python - 线程 django-main-thread django 中的异常