1
我想交換列表中的2個元素。請看下面這段代碼:即使元素存在於Python中的列表中也存在值錯誤
>>>a=[1,2,3,4]
>>>a[a.index(2)], a[a.index(2)-1] = a[a.index(2)-1], a[a.index(2)]
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
a[a.index(2)], a[a.index(2)-1] = a[a.index(2)-1], a[a.index(2)]
ValueError: 2 is not in list
我試圖交換1和2分別存在於索引0和1。即使列表中存在2,我也會遇到值錯誤。任何人都可以請解釋爲什麼是這樣嗎?
@PeterWood沒有。左到右。 –