Skip to main content
 首页 » 编程设计

python之为什么列表是其大小的两倍

2025年05月04日9lyhabc

对于给定的列表:

x = [x for x in range(10)] 

打印出索引和值:

for i in range(-10, len(x)): 
    print i, ": ", x[i] 

输出是:

-10 :  0 
-9 :  1 
-8 :  2 
-7 :  3 
-6 :  4 
-5 :  5 
-4 :  6 
-3 :  7 
-2 :  8 
-1 :  9 
0 :  0 
1 :  1 
2 :  2 
3 :  3 
4 :  4 
5 :  5 
6 :  6 
7 :  7 
8 :  8 
9 :  9 

但是

print x 

返回:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

为什么实际列表是初始化列表的两倍?

请您参考如下方法:

您正在使用负索引。那些也有用;在 Python 中,索引 < 0 从末尾开始索引。所以有两种不同的方式索引元素,从开始和结束计数。

例如,索引 2 和 -8 都引用 x 中的第 3 个元素,所以两个索引都给你值 2。

因此,列表的长度不是原来的两倍,您只是将值打印了两次;一次用于负指数,一次用于正指数。

请参阅 sequence types operations table 下的注释 #3 :

  1. If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

或来自 Introduction section of the Python tutorial :

Indices may also be negative numbers, to start counting from the right:

>>> word[-1]  # last character 
'n' 
>>> word[-2]  # second-last character 
'o'