我試圖在有序列表中添加一個值,但該列表將不會改變:爲什麼列表不變?
def insert(V, x):
if len(V)!=0:
for i in range(0 , len(V)-1):
if (V[i]<=x)and(V[i+1]>=x):
V=V[0:i+1]+[x]+V[i+1:len(V)]
print("\nExpected: \n"+ repr(V))
return
V=V+[x]
return
我有這樣的:
V=[1,2,3,4,5,6,7,8,9,10]
insert(V, 6)
print("\nResult: \n"+ repr(V))enter code here
,這是結果:
Expected:
[1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10]
Result:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
我可以解決問題設置V作爲返回,但我希望該功能在列表上工作。
可能的重複[python;修改列表中的函數](https://stackoverflow.com/questions/22054698/python-modifying-list-inside-a-function) – AChampion
是否有你不能使用'list.insert()'的原因? –
'''v。插入(索引,值)''' –