Bisect in Python is used to manipulate arrays of sorts, such as when you are inserting data into an array. The following code demonstrates how to do this:
The output is:
New Pos Contents----------------- 0 [+] 1 [+], 1 [+, 2, 1] [+] [+ ] [2, +, 26, [+]--[+]-------------------------- , the ten, Ten, [] 0 [Ten, +, +, 3, 9,, and ten, , and 0 [3 ], (+), (+), (+), (+), (-) [3, ten, (+), (4), (+), (+), +, 3, 3, 10, (+), +/--), and 1, 9 4, 3, 10, 14, 26, 44, 45, 50, 66, 77, and 1 0 [1, 77, +---------
As you can see, the array is sorted at the same time as these random numbers are inserted. However, there are some repeating elements, such as the above 77, 77. You can set the order of these repeating elements, if you want the repeating element to appear on the left side of the same element as he is using bisect_left, otherwise it is used bisect_right, the corresponding use Insort_left and insort_right. For example, the following code, we can see the duplicate element index changes:
Import Bisectimport randomrandom.seed (1) Print (' New pos contents ') Print ('-----------------') l=[] for I in range (1,15): C0/>r=random.randint (1,100) position=bisect.bisect_left (l,r) bisect.insort_left (l,r) print '%3d%3d ' % (r,position), L
The output is:
New Pos Contents----------------- 0 [+] 1 [+], 1 [+, 2, 1] [+] [+ ] [2, +, 26, [+]-------------------------------------- 0 [Ten, +,----------] 3 0 [3, ten, +,------------ 5/>9 [3, ten, (+,), A, 4, ten,, 3, 1, 3, [8]] (+), (+), (+), (+ 0, +,------------------------------ 1 0 [1, 3, 10, 14, 26, 44, 45, 50, 66, 77, 77]
This function bisect.bisect (List,key), like the tailmap of TreeMap in Java (Fromkey)