Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

python - How to find an index at which a new item can be inserted into sorted list and keep it sorted?

a = 132

b = [0, 10, 30, 60, 100, 150, 210, 280, 340, 480, 530]

I want to know that a should be in the 6th position in ordered list b.

What's the most pythonic way to do so?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

bisect is a module in the Python Standard Library that is perfect for this task. The function bisect in the module bisect will give you the index of the insertion point for the value.

Let me give a code example for bisect

from bisect import bisect
a = 132
b = [0, 10, 30, 60, 100, 150, 210, 280, 340, 480, 530]
print(bisect(b, a))

The result will be 5 because the list is 0-based, so in fact it is the 6th position.

What you can do know is to use the result for an insert.

index = bisect(b, a)
b.insert(index, a)

or without the intermediate variable

b.insert(bisect(b, a), a)

Now b will be [0, 10, 30, 60, 100, 132, 150, 210, 280, 340, 480, 530].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...