我有一个包含一组元素的数组。我想把一个给定的元素放在前面,但是在其他情况下保持顺序不变。对于这个问题最干净的语法,大家有什么建议吗?
这是我能想到的最好的方法,但是当 N 个运算可以做的时候,使用 N 个 logN 运算似乎不太好。
mylist = sorted(mylist, key=lambda x: x == targetvalue, reverse=True)
To bring (for example) the 6th element to the front, use:
mylist.insert(0, mylist.pop(5))
(python uses the standard 0 based indexing)
I would go with:
mylist.insert(0, mylist.pop(mylist.index(targetvalue)))
Note: the following code (and the sample code you offered) will put all matching elements at the front.
x = targetvalue for i in range(len(mylist)): if(mylist[i] == x): mylist = [mylist[i]] + mylist[:i] + mylist[i+1:]
For example, if mylist = [1, 2, 3, 4, 3] and x = 3, this will result in [3, 3, 1, 2, 4].
This requires just two list operations (no index): mylist.remove(targetvalue) mylist.insert(0, targetvalue)
mylist.remove(targetvalue) mylist.insert(0, targetvalue)