[英]How to use list[list.index('')] queries in python
我在python IDLE中嘗試了以下代碼。 但我似乎沒有找到交換的元素。
>>> a = [1,2,3,4,5,6,7]
>>> if(a.index(2)<a.index(4)):
... a[a.index(2)],a[a.index(4)] = a[a.index(4)],a[a.index(2)]
根據代碼,它應該反轉2和4的位置糾正我如果我錯了。
賦值列表表達式在分配時從左到右進行計算。
這是發生的事情:
(4, 2)
a[a.index(2)]
被評估為分配4
, a[2]
被改變,列表變為a[a.index(2)]
[1, 4, 3, 4, 5, 6, 7]
a[a.index(4)]
被評估為分配2
, a[2]
再次被改變,因為現在第一個位置4
又回到[1, 2, 3, 4, 5, 6, 7]
。 您可以在反匯編的Python字節代碼中看到這一點:
>>> def foo():
... a = [1,2,3,4,5,6,7]
... a[a.index(2)],a[a.index(4)] = a[a.index(4)],a[a.index(2)]
...
>>> import dis
>>> dis.dis(foo)
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
9 LOAD_CONST 4 (4)
12 LOAD_CONST 5 (5)
15 LOAD_CONST 6 (6)
18 LOAD_CONST 7 (7)
21 BUILD_LIST 7
24 STORE_FAST 0 (a)
3 27 LOAD_FAST 0 (a)
30 LOAD_FAST 0 (a)
33 LOAD_ATTR 0 (index)
36 LOAD_CONST 4 (4)
39 CALL_FUNCTION 1
42 BINARY_SUBSCR
43 LOAD_FAST 0 (a)
46 LOAD_FAST 0 (a)
49 LOAD_ATTR 0 (index)
52 LOAD_CONST 2 (2)
55 CALL_FUNCTION 1
58 BINARY_SUBSCR
59 ROT_TWO
60 LOAD_FAST 0 (a)
63 LOAD_FAST 0 (a)
66 LOAD_ATTR 0 (index)
69 LOAD_CONST 2 (2)
72 CALL_FUNCTION 1
75 STORE_SUBSCR
76 LOAD_FAST 0 (a)
79 LOAD_FAST 0 (a)
82 LOAD_ATTR 0 (index)
85 LOAD_CONST 4 (4)
88 CALL_FUNCTION 1
91 STORE_SUBSCR
92 LOAD_CONST 0 (None)
95 RETURN_VALUE
通過指令索引59,Python已經評估了右側表達式; 接下來是作業。 可以看到, a.index(2)
(63-72)的第一評估,然后在STORE_SUBSCR
存儲4
, 才把 a.index(4)
進行評估(指令79-85)。
解決方法是為每個值調用.index()
一次 ,並將索引存儲在變量中:
index_two, index_four = a.index(2), a.index(4)
if index_two < index_four:
a[index_two], a[index_four] = a[index_four], a[index_two]
Martijn的答案已經完成,並解釋了您遇到的問題。 如果您仍然想知道如何編寫符合您需要的代碼,請嘗試以下方法:
if (a.index(2) < a.index(4)):
x,y = a.index(4),a.index(2)
a[x],a[y] = a[y],a[x]
這里的想法基本上只是將index
返回值存儲在List本身之外的東西中。 像這樣分開保存指數可以避免你遇到的競爭條件。
為避免這種情況,您可以將.index()
調用的結果存儲在變量中,然后與它們進行交換:
>>> a = [1,2,3,4,5,6,7]
>>> i2 = a.index(2)
>>> i4 = a.index(4)
>>> if i2<i4:
... a[i2], a[i4] = a[i4], a[i2]
>>> a
[1, 4, 3, 2, 5, 6, 7]
這樣,當一次足夠時,你也避免調用該方法三次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.