问题:在列表中移动项目?

在Python中,如何将项目移至列表中的确定索引?

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


回答 0

使用insert列表的方法:

l = list(...)
l.insert(index, item)

另外,您可以使用切片符号:

l[index:index] = [item]

如果要将列表中已经存在的项目移动到指定位置,则必须将其删除并将其插入新位置:

l.insert(newindex, l.pop(oldindex))

Use the insert method of a list:

l = list(...)
l.insert(index, item)

Alternatively, you can use a slice notation:

l[index:index] = [item]

If you want to move an item that’s already in the list to the specified position, you would have to delete it and insert it at the new position:

l.insert(newindex, l.pop(oldindex))

回答 1

稍微短一点的解决方案,它只将项目移到末尾,而不是在任何地方:

l += [l.pop(0)]

例如:

>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]

A slightly shorter solution, that only moves the item to the end, not anywhere is this:

l += [l.pop(0)]

For example:

>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]

回答 2

如果您不知道商品的位置,则可能需要先找到索引:

old_index = list1.index(item)

然后移动它:

list1.insert(new_index, list1.pop(old_index))

或恕我直言,更干净的方法:

try:
  list1.remove(item)
  list1.insert(new_index, item)
except ValueError:
  pass

If you don’t know the position of the item, you may need to find the index first:

old_index = list1.index(item)

then move it:

list1.insert(new_index, list1.pop(old_index))

or IMHO a cleaner way:

try:
  list1.remove(item)
  list1.insert(new_index, item)
except ValueError:
  pass

回答 3

解决方案非常简单,但是您必须知道原始位置的索引和新位置的索引:

list1[index1],list1[index2]=list1[index2],list1[index1]

A solution very simple, but you have to know the index of the original position and the index of the new position:

list1[index1],list1[index2]=list1[index2],list1[index1]

回答 4

我介绍了一些方法,可以通过timeit在同一列表中移动项目。如果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))│
──────────┴────────┘

这里是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]│
┘──────────┴─────────┘

如果仅使用几次,则不会有太大的区别,但是如果您进行繁重的工作(如手动分拣),则选择最快的就很重要。否则,我建议您只阅读您认为最易读的内容。

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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。