我正在做一个简单的负索引列表,而类的循环,我不明白为什么它不能正常工作。你知道吗
代替打印:
4个
三
二
1个
我得到:
1个
4个
三
二
如果能帮我指出我做错了什么,我将不胜感激。 提前谢谢!你知道吗
教授练习:
def loop_using_negative_indexes(my_list):
"""
03. Access all the items in a list with negative indexes
Finish this function below which takes a list as parameter and prints the items in a reversed order.
You should do this with negative indexes,
e.g. my_list[-1] is the last item and my_list[-2] is the 2nd last.
You can choose to use either for loop or while loop to do this.
There is no explicit return value of this function.
"""
我的编码:
i = 0
while i < len(my_list):
print(my_list[-i])
i += 1
教授考试:
#test for Q3
new_list = [1,2,3,4]
loop_using_negative_indexes(new_list)
使用带有^{} 的
for
循环:enumerate()
用于从1开始生成索引。我们不需要enumerate()
返回的列表中的值,因此它们被绑定到_
以表示我们不在乎。使用enumerate()
比使用for i in range(1, len(my_list)+1):
要干净一些,尽管执行起来会慢一些。你知道吗使用
while
循环,可以从1而不是0开始计数器:-0仍然是0。因此,backward indexing是基于1的(或者可能是基于-1的)。你可以直接写
或间接地(用更少的-1)
或者,当不是家庭作业的时候,更像是恶作剧
你只是犯了几个一个接一个的错误。你知道吗
正如我在评论中所说的,
-0 == 0
,所以a[-0]
与a[0]
相同,即它访问a
中的第一项。你知道吗这是你的代码的修复版本。你知道吗
输出
正如Davis-Herring提到的,直接迭代序列中的项比通过索引间接地进行迭代更具python风格。OTOH,做这样的练习很重要,练习使用指数来发展你对指数如何工作的理解。你知道吗
相关问题 更多 >
编程相关推荐