简体   繁体   中英

Python Enumerate Function Auto Sorts

When I run this code here:

nums = [1,7,3,4,10]
sorts = nums
sorts.sort()
count=0
for i,e in enumerate(nums):
    print(i,e)
    if sorts[i] != e:
        count+=1

print(count)

the i and e values inside the enumerate loop seem to be auto sorted. However, once I remove the sorts.sort(), it doesn't auto sort. Why is this?

The name nums is a reference represents the [1,7,3,4,10] list.

Line 2, you create a new name sorts that also represents that same list.

Line 3, you use sorts.sort() to sort it, so it changes the same list that nums represented. Hence, it is not auto-sort.

If you remove the sorts.sort() , then the nums list will keep the same.

well obviously. if you don't sort them then they will not be sorted.. the program doesn't update the list from run to run.

You used a sort method. Remove it and you will get your values listed the way it is in the list.

by declaring sorts = nums you've made a shallow copy of sorts and so by calling sort() , the references are sorted in memory and the nums list will be using those references. if you want a deep copy do this: sorts = [i for i in nums] . The enumerate function will of course always produce an incrementation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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