与以下python列表的输出相混淆 [英] Confused with the output of the following python list

查看:63
本文介绍了与以下python列表的输出相混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我看到这段代码以来,我就感到困惑.

Ever since I saw this code, I am getting confused.

a=[0,1,2,3]

for a[-1] in a:
   print(a[-1])

因此,根据代码,a [-1]应该是最后一个元素,即3,因此代码应根据我的要求输出以下输出:

So according to code, a[-1] should be the last element, which is 3, and hence the code should print the following output according to me:

3
2 
1
0

但是我得到的输出如下:

But the output I got was the following:

0
1
2
2

任何人都可以通过逐步迭代来帮助执行以下代码.

Can anybody help how the following code is getting executed hopefully with a step by step iteration.

推荐答案

要了解您的代码的作用,首先,让我们看一下下面的代码的作用:

To understand what your code does, first, let's see what below code does:


    a = [0,1,2,3]
    for item in a:
        print(item)

此代码可以转换为以下基于索引的for循环:

This code can be converted to the following index-based for loop:


    for i in range(len(a)):
        item = a[i]
        print(item)

上述摘要的输出

0
1
2
3

在上面的代码中,您要从左到右依次遍历列表 a ,并将每个值分配给变量 item .然后,您将打印该项目变量.

In the above code, you are iterating over the list a, one by one in left to right order and assigning each value to the variable item. Then you are printing that item variable.

现在,进入代码的工作,让我们将其转换为基于索引的for循环

Now, coming to what your code does, let's convert it to index-based for loop


    for i in range(len(a)):
        a[-1] = a[i] # See, how you are re-assigning the last element of list
        print(a[-1])

在每次迭代中, i a [i] a 的值如下:

At each iteration, value of i , a[i] and a would be as following:

first iteration, i =0, a[i] = 0, a = [0,1,2,0], output of a[-1] = 0
second iteration, i = 1, a[i] = 1, a = [0,1,2,1], output of a[-1] = 1
third iteration, i = 2, a[i] = 2, a = [0,1,2,2], output of a[-1] = 2
final iteration, i = 3, a[i] = 2, a = [0,1,2,2], output of a[-1] = 2

这就是您看到输出为0、1、2、2的原因

That's the reason you are seeing the output as 0,1,2,2

如果要以相反的顺序打印数组,则不应将值分配给数组的最后一个元素,请按如下所示修改代码

If you want to print the array in reverse order, you shouldn't assign the values to last element of array, modify your code as below


    for item in a[::-1]
     print (item)

这里[[::-1]反转数组,然后使用作用域变量项迭代反转数组.

Here a[::-1] reverses the array, and then you are using a scoped variable item to iterate over the reversed array.

这篇关于与以下python列表的输出相混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆