简单的负数索引列表。不明白为什么不能正常工作:/

2024-03-29 00:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个简单的负索引列表,而类的循环,我不明白为什么它不能正常工作。你知道吗

代替打印:

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)

Tags: andtheinloopismywithitems
3条回答

使用带有^{}for循环:

my_list = [1, 2, 3, 4]
for i, _ in enumerate(my_list, 1):
    print(my_list[-i])

enumerate()用于从1开始生成索引。我们不需要enumerate()返回的列表中的值,因此它们被绑定到_以表示我们不在乎。使用enumerate()比使用for i in range(1, len(my_list)+1):要干净一些,尽管执行起来会慢一些。你知道吗

使用while循环,可以从1而不是0开始计数器:

i = 1
while i <= len(my_list):
    print(my_list[-i])
    i += 1

-0仍然是0。因此,backward indexing是基于1的(或者可能是基于-1的)。你可以直接写

for i in range(-1,-len(my_list)-1,-1):

或间接地(用更少的-1)

for i in range(len(my_list)):
  print(my_list[-i-1])

或者,当不是家庭作业的时候,更像是恶作剧

for x in reversed(my_list):

你只是犯了几个一个接一个的错误。你知道吗

正如我在评论中所说的,-0 == 0,所以a[-0]a[0]相同,即它访问a中的第一项。你知道吗

这是你的代码的修复版本。你知道吗

my_list = [1, 2, 3, 4]

i = 1
while i <= len(my_list):
    print(my_list[-i])
    i += 1

输出

4
3
2
1

正如Davis-Herring提到的,直接迭代序列中的项比通过索引间接地进行迭代更具python风格。OTOH,做这样的练习很重要,练习使用指数来发展你对指数如何工作的理解。你知道吗

相关问题 更多 >