Python函数调用后主函数列表变量a异常改变问题求助
a Gets Modified Unexpectedly Hey there! Let's break down why your original list a is changing even though you didn't intend to modify it in the mhmArgSort function.
The Core Issue: Mutable Object References in Python
In Python, lists are mutable objects. When you write myNumList = myNumListInput inside your function, you're not creating a brand new copy of the input list—you're just making myNumList point to the exact same list as myNumListInput (they share the same memory address).
So when you execute myNumList[smallestNumIndex] = 100000000000, you're directly altering the original list a from your main scope, because they're the same underlying object.
The Fix: Work With a Copy of the List
To avoid modifying the original list, you need to create a shallow copy of the input list before performing any operations on it. Here are three simple ways to do this:
- Use the built-in
copy()method:myNumList = myNumListInput.copy() - Use the
list()constructor:myNumList = list(myNumListInput) - Use slicing syntax:
myNumList = myNumListInput[:]
Modified Working Code
Here's your updated function with the copy fix applied:
def mhmArgSort(myNumListInput): # Create a copy of the input list to avoid altering the original myNumList = myNumListInput.copy() cnt=0 endCnt=len(myNumList) NumListSortedIndices=[] for cnt1 in range(len(myNumList)): smallestNum=100000000000 smallestNumIndex=0 for cnt in range(len(myNumList)): if myNumList[cnt]<smallestNum: smallestNum=myNumList[cnt] smallestNumIndex=cnt NumListSortedIndices.append(smallestNumIndex) myNumList[smallestNumIndex]=100000000000 return NumListSortedIndices a=[1,2,3,4,-1,0,3] print(a) b=mhmArgSort(a) print(a) print(b)
Updated Output
[1, 2, 3, 4, -1, 0, 3] [1, 2, 3, 4, -1, 0, 3] [4, 5, 0, 1, 2, 6, 3]
Now your original list a remains unchanged, and you get the correct sorted indices in b as expected.
内容的提问来源于stack exchange,提问作者Moe

