简体   繁体   English

python 3:列表的值在进入for循环时发生变化

[英]python 3 : values of a list change when it enters a for loop

Challenge : to find the minimum and maximum sums which can be obtained out of four elements from the list containing 5 elements. 挑战:找到可从包含5个元素的列表中的四个元素中获得的最小和最大总和。

Approach followed : Sort the list in descending and ascending order and store them into two different variables. 接下来的方法:按降序和升序对列表进行排序,并将它们存储到两个不同的变量中。 Finding the sum of first 4 elements in both of the lists. 找到两个列表中前4个元素的总和。 One sum would be the minimum most and the second one would be the maximum most. 一个总和是最小的,第二个是最大的。

Code : 代码:

arr = [2,1,3,4,5]
arr.sort()
asc = arr
print(asc[0],asc[1],asc[2],asc[3])
arr.sort(reverse = True)
des = arr
print(des[0],des[1],des[2],des[3])
maxi = 0
mini = 0
for j in range(4) :
    mini = mini + asc[j]
    print(mini, asc[j])
    maxi = maxi + des[j]
    print(maxi,des[j])
print(mini, maxi)

Few print statements are introduced here for debugging purpose. 这里引入的打印语句很少用于调试目的。 As visible in the code, bot the sorted versions are printed before entering into the for loop and after entering into the loop. 在代码中可见,bot在进入for循环之前和进入循环之后打印已排序的版本。 Its clearly visible as seen in the output that, the list which should be holding the elements in ascending order is having the elements in the descending order. 如输出中所见,它清晰可见,应该按升序保持元素的列表具有降序的元素。

Output : 输出:

11 12 13 14 - list in the ascending order
15 14 13 12 - list in the descending order

15 15 - round 0
15 15

29 14 - round 1
29 14

42 13 - round 2
42 13

54 12 - round 3
54 12

54 54 - final output

why the elements present in one particular list change their order when they enter into the for loop ?? 为什么一个特定列表中的元素在进入for循环时会改变它们的顺序?

When you are doing asc = arr and des = arr a new list is not created. 当您执行asc = arrdes = arr不会创建新列表。 asc , des and arr are linked to one list object so whey you change any of them all variables will be changed as it's single object. ascdesarr链接到一个列表对象,所以当你改变它们中的任何一个时,所有变量都将被改变,因为它是单个对象。

In [1]: a = [1, 2]

In [2]: b = a

In [3]: id(a), id(b)
Out[3]: (140601802913048, 140601802913048)

In [4]: b = a[:]

In [5]: id(a), id(b)
Out[5]: (140601802913048, 140601819243872)

If you want to have a copy of list do 如果你想拥有一份清单副本

asc = arr[:]
des = arr[:]

You need to do: 你需要这样做:

asc = arr.copy()
# or asc = arr[:]

Or else, when arr is sorted reverse, asc also changes. 否则,当arr反向排序时, asc也会发生变化。 asc is a pointer to the array and when arr changes, asc changes. asc是指向数组的指针,当arr更改时, asc发生变化。 Better, you create a copy of arr , so changes won't reflect back. 更好的是,您创建了一个arr的副本,因此更改不会反映出来。


The whole code you have written can be condensed into these two lines: 您编写的整个代码可以压缩为以下两行:

 arr = [2,1,3,4,5] print(sum(sorted(arr)[:4])) # 10 print(sum(sorted(arr, reverse=True)[:4])) # 14 # Or print(sum(sorted(arr)[-4:])) instead of the last print. 

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

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