[英]Inserting an element in a list while keeping the order
I have an ordered list a=[1.1, 2., 4.5]
.我有一个有序列表a=[1.1, 2., 4.5]
。 I want to create a new list b
consisting in the previous list with an element l=3.1
inserted in such a way that b
is still ordered.我想创建一个包含在前一个列表中的新列表b
其中元素l=3.1
以b
仍然排序的方式插入。
I would do it using numpy
in the following way:我会通过以下方式使用numpy
来做到这一点:
import numpy as np
b=a[:np.searchsorted(a, l)]+[l]+a[np.searchsorted(a, l):]
are there more synthetic ways, for example with some specific numpy
function ?是否有更多合成方法,例如使用某些特定的numpy
函数?
In general, you can use bisect.insort_left
一般来说,你可以使用bisect.insort_left
from bisect import insort_left
a=[1.1, 2., 4.5]
insort_left(a, 3.1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.