首页 > 解决方案 > 你能解释为什么这个 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, '')。为什么会这样?

标签: pythonlistindexingtuples

解决方案


Python 中的负索引(链接)意味着你从列表的末尾开始,所以_magnitude_list[-1]会给你列表的最后一个元素。

由于您在这里有一个多维结构 - 2 元素元组列表,_magnitude_list[-1]将为您提供整个最后一个元组,并且_magnitude_list[-1][0]只为您提供最后一个元组中的第一个元素。

与索引的 0 值类似 - 它会给你列表的第一个元素,在你的情况下_magnitude_list[0]会给你列表中的整个第一个元组。


推荐阅读