循环时简单的负面索引列表。不明白为什么它不能正常工作:/

时间:2017-10-12 01:52:52

标签: python list indexing while-loop

我正在制作一个简单的否定索引列表,同时循环上课,我不明白为什么它无法正常工作。

而不是打印:

4

3

2

1

我得到了:

1

4

3

2

任何帮助指出我做错了什么都会非常感激。 提前谢谢!

教授的练习:

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)

3 个答案:

答案 0 :(得分:0)

-0仍为0.因此,backward indexing基于1(或者基于-1)。你可以直接写

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

或间接(少于-1s)

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

或者,当它不是家庭作业时,更多的是Python,

for x in reversed(my_list):

答案 1 :(得分:0)

你只有几个一个一个错误。

正如我在评论-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

正如戴维斯·赫林所提到的,更多的是Pythonic直接迭代序列中的项目,而不是通过索引间接地进行迭代。 OTOH,做这样的练习很重要,练习使用索引来培养你对指数如何运作的理解。

答案 2 :(得分:0)

使用for循环enumerate()

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