Move an item inside a list?

前端 未结 6 531
-上瘾入骨i
-上瘾入骨i 2020-11-29 01:58

In Python, how do I move an item to a definite index in a list?

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 02:55

    I profiled a few methods to move an item within the same list with timeit. Here are the ones to use if j>i:

    ┌──────────┬──────────────────────┐
    │ 14.4usec │ x[i:i]=x.pop(j),     │
    │ 14.5usec │ x[i:i]=[x.pop(j)]    │
    │ 15.2usec │ x.insert(i,x.pop(j)) │
    └──────────┴──────────────────────┘
    

    and here the ones to use if j<=i:

    ┌──────────┬───────────────────────────┐
    │ 14.4usec │ x[i:i]=x[j],;del x[j]     │
    │ 14.4usec │ x[i:i]=[x[j]];del x[j]    │
    │ 15.4usec │ x.insert(i,x[j]);del x[j] │
    └──────────┴───────────────────────────┘
    

    Not a huge difference if you only use it a few times, but if you do heavy stuff like manual sorting, it's important to take the fastest one. Otherwise, I'd recommend just taking the one that you think is most readable.

提交回复
热议问题