简体   繁体   中英

Inserting an element in a list while keeping the order

I have an ordered list 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.

I would do it using numpy in the following way:

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 ?

In general, you can use bisect.insort_left

from bisect import insort_left
a=[1.1, 2., 4.5]
insort_left(a, 3.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM