Python 为什么要从这个列表的长度中减去一个?
我在网上看到了这段代码,我需要帮助弄清楚这段代码的作用Python 为什么要从这个列表的长度中减去一个?,python,Python,我在网上看到了这段代码,我需要帮助弄清楚这段代码的作用 words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1 words=[“你好”、“世界”、“垃圾邮件”、“鸡蛋”]
words = ["hello", "world", "spam", "eggs"]
counter = 0
max_index = len(words) - 1
while counter <= max_index:
word = words[counter]
print(word + "!")
counter = counter + 1
words=[“你好”、“世界”、“垃圾邮件”、“鸡蛋”]
计数器=0
最大索引=len(字)-1
计数器时,您的代码可能如下所示:
counter = 0
words = ["hello", "world", "spam", "eggs"]
max_index = len(words) - 1
while counter <= max_index:
word = words[counter]
print(word + "!")
counter = counter + 1
这做了完全相同的事情,但是现在您直接迭代列表中的单词,没有任何不必要的变量。它不必是“forwordin words”,也可以是“forelementin iterable”。因为程序循环直到counter>max\u index
- 如果
max\u index==4
(len(words)
),则您的程序将尝试设置word=words[4]
,但将失败,因为索引4
处的words
中没有任何内容
- 如果
max_index==3
(len(words)-1
),那么您的程序将永远无法到达计数器==4
,并且您的程序将正常工作
Python列表的索引为零。这意味着列表中的第一个索引由0
而不是1
访问。在代码中,正在计算列表的最大索引
len()
内置函数返回列表的长度。但是如果您试图使用len()
返回的值,Python将引发一个索引器
:
>>> l = ["hello", "world", "spam", "eggs"]
>>> l[len(l)]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
l[len(l)]
IndexError: list index out of range
>>>
箱子的数量是四个。有四个盒子。但是没有第四个指数,只有第三个指数。Python开始计算列表中第一位的“盒子”数量。但是Python开始在数字0处计算每个“框”的索引
这意味着列表的最大索引(您可以在[]
中输入的最大数字)将始终小于列表的长度。因此,要获得列表的最大索引,必须从列表长度中减去一:
>>> l = ["hello", "world", "spam", "eggs"]
>>> l[len(l) - 1] # subtract one and this will work
'eggs'
>>>
Python列表的索引从零开始。因此,如果列表中有四个元素,那么最后一个索引将是三个。这就是为什么-1
但是这不是python的惯用用法,因为对于word-in-words:print(word+“!”
或者甚至是简单的print('\n'.join(word+“!”对于word-in-words))
在没有max\u index
和counter
@AChampion的情况下也会做同样的事情,这是真的,但我认为OP并没有要求我们更改代码。“我只是想解释一下。”蒂莫特里读了回答规则。说“不要那样做,而是这样做”是很好的。但这甚至不是一个答案,这只是一个评论。@MohammadYusufGhazi我并不是说这个评论违反了任何规则。我只是说我不认为这个评论会对OP有所帮助。我知道他们是这个while循环的for循环,这在课程中引起了我的注意,我不明白的是for循环中的-1,我是说Python中的(while)loopindex以0开头,这意味着长度为4的列表中最后一个元素的索引实际上是3-因此,max_索引变量为-1。因此,将max_索引分配给len(单词)会使列表变为0,1,2,3,4,而不是0,1,2,3。因此,我们减去1以删除max_索引。我能收到你的电子邮件吗?
0 1 2 3
|---------||---------||---------||---------|
| "hello" || "world" || "spam" || "eggs" |
|---------||---------||---------||---------|
1 2 3 4
>>> l = ["hello", "world", "spam", "eggs"]
>>> l[len(l) - 1] # subtract one and this will work
'eggs'
>>>