简体   繁体   English

python - 为什么这个列表输出?

[英]python - why this output of list?

I want to understand what A[A[i]] means in this code:我想了解此代码中A[A[i]]的含义:

A = [1,4,2,0,3]
temp = A[0]

for i in range(len(A)-1):
    A[i] = A[i+1]

A[len(A)-1] = temp

for i in range (len(A)):
    print(A[A[i]], end ="" )

output :输出 :

10432
Process finished with exit code 0

I know the output but I need to understand how did we get it, specially this part:我知道输出,但我需要了解我们是如何得到它的,特别是这部分:

print(A[A[i]], end ="" )

what does A[A[i]] mean? A[A[i]]是什么意思?

A[A[i]] is just the element of A with index A[i] . A[A[i]]只是A中索引为A[i]的元素。 For example, if you have A = [1, 2] , A[A[i]] = 2 if i = 0 because A[0] = 1 so A[A[0]] = A[1] = 2 .例如,如果您有A = [1, 2] ,则A[A[i]] = 2如果i = 0因为A[0] = 1所以A[A[0]] = A[1] = 2

And for your information, end="" just means that python won't skip a line after printing the value.并且为了您的信息, end=""只是意味着 python 在打印值后不会跳过一行。

All the elements of: A = [1,4,2,0,3] are also, by coincidence valid indexes into A .巧合的是, A = [1,4,2,0,3]的所有元素也是A的有效索引。

Note that the list A has 5 elements and each element is in the range 0..4 .请注意,列表A有 5 个元素,每个元素都在0..4范围内。

This means that for any A[i] where i is a valid index retrieves one of the values, which itself is a valid index.这意味着对于i是有效索引的任何A[i]都会检索其中一个值,该值本身就是有效索引。

So, looking at the last two lines:所以,看看最后两行:

for i in range (len(A)):
    print(A[A[i]], end ="" )

we can see that the for loop causes i to be a valid index each time round, therefore A[i] is a valid index, therefore A[A[i]] returns one of the values from A .我们可以看到for循环每次都使i成为有效索引,因此A[i]是有效索引,因此A[A[i]]返回来自A的值之一。

After Evaluating the following piece of code:评估以下代码后:

A=[1,4,2,0,3]
temp = A[0]
for i in range(len(A)-1):
    A[i] = A[i+1]
A[len(A)-1] = temp

we get the updated array: A=[4,2,0,3,1] Now the remaining piece of code can be evaluated as:我们得到更新后的数组: A=[4,2,0,3,1] 现在剩下的代码可以计算为:

  1. for i=0 we have A[A[0]]=A[4]=1;对于 i=0 我们有 A[A[0]]=A[4]=1;
  2. for i=1 we have A[A[1]]=A[2]=0;对于 i=1 我们有 A[A[1]]=A[2]=0;
  3. for i=2 we have A[A[2]]=A[0]=4;对于 i=2 我们有 A[A[2]]=A[0]=4;
  4. for i=3 we have A[A[3]]=A[3]=3;对于 i=3 我们有 A[A[3]]=A[3]=3;
  5. for i=4 we have A[A[4]]=A[1]=2;对于 i=4 我们有 A[A[4]]=A[1]=2;

As format is given as => end="" the result is printed as : 10432由于格式为 => end="",因此结果打印为:10432

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM