在 python 中,您可以像这样更改列表:
In [303]: x = [1,2,3,4,5,6]
In [304]: x[x <= 3]+=3
In [305]: x
Out[306]: [4, 2, 3, 4, 5, 6]
我已经知道这件事有一段时间了,但我认为我并不完全了解幕后发生的事情。如果有人愿意花时间解释,我会很高兴。
In [307]: x = [1,2,3,4,5,6]
In [308]: dis.dis('x[x <= 3]+=3')
0 SETUP_LOOP 30811 (to 30814)
3 SLICE+2
4 STORE_SUBSCR
5 DELETE_SUBSCR
6 SLICE+2
7 DELETE_SLICE+1
8 FOR_ITER 15659 (to 15670)
11 DELETE_SLICE+1
In [309]: x
Out[309]: [1, 2, 3, 4, 5, 6]
In [310]: x[x <= 3]+=3
In [311]: x
Out[311]: [4, 2, 3, 4, 5, 6]
In [312]: x<=3
Out[312]: False
In [313]: x[False]+=3
In [314]: x
Out[314]: [7, 2, 3, 4, 5, 6]