在列表中查找插入点

在列表中查找插入点

或具有生成器理解力 n = sum(y> x [i] for i in range(len(x))) - 1 但必须有一个更清洁的方式,因为第一种方法是笨重的 并且不适应更改列表长度,第二种方法不是 对于代码的随意读者来说很明显。 我的列表通常会有2到5个项目,因此速度不是很大的问题。我'感谢你的指导。 真诚 托玛s飞利浦I have an ordered list e.g. x = [0, 100, 200, 1000], and given anypositive integer y, I want to determine its appropriate position inthe list (i.e the point at which I would have to insert it in order tokeep the list sorted. I can clearly do this with a series of ifstatements:if y<x[1]: n = 0elif y < x[2]: n = 1elif y < x[3]: n = 2else: n = 3Or with a generator comprehensionn = sum ( y>x[i] for i in range(len(x)) ) - 1But there has to be a cleaner way, as the first approach is unwieldyand does not adapt to changing list lengths, and the second is notobvious to a casual reader of the code.My list will typically have 2 to 5 items, so speed is not a hugeissue. I''d appreciate your guidance.SincerelyThomas Philips 列表通常会有2到5个项目?保持简单! x.append(y) x.sort() - 保罗List "will typically have 2 to 5 items"? Keep it simple!x.append(y)x.sort()-- Paul 这篇关于在列表中查找插入点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-14 22:52