我有两份清单:
threshold=[0.123,0.108,0.102,0.087]
retention=[0.19,1,0.57,5,0.09]
我想知道每个retention
元素是否在threshold
列表中
我的代码在此说明:
ca2=[(b>retention[0]>a) for b,a in zip(threshold[::1],threshold[1::1])]
ca3=[(b>retention[1]>a) for b,a in zip(threshold[::1],threshold[1::1])]
ca4=[(b>retention[2]>a) for b,a in zip(threshold[::1],threshold[1::1])]
ca5=[(b>retention[3]>a) for b,a in zip(threshold[::1],threshold[1::1])]
ca6=[(b>retention[4]>a) for b,a in zip(threshold[::1],threshold[1::1])]
如您所见,它请求retention[0]
是否在threshold
中的哪个元素之间
我需要比较retention
中的每个元素。我的代码可以工作,但它是多余的,我认为没有效率。我还想自动与threshold
中的另外两个元素进行比较。如果您能指导我或帮助我提高代码的效率,我将不胜感激,因为保留列表可能会更长
不完全确定您想要实现什么,但是您可以使用
bisect
在阈值列表中进行二进制搜索,以找到刚好低于给定数字的阈值与另一个
bisect
答案(这会产生非常不同的输出)一样,对于retention
中的k个元素,每个查询的复杂性是O(logn),n是阈值的数目,总共O(klogn)您可以生成一个字典,其中保留值作为键,阈值比较列表作为值。此外,如果将zip对象强制转换为列表,则不需要每次迭代都创建它
要检查每个保留元素是否在阈值的两个元素之间,可以使用对分(即每次检查的日志(n)时间)
代码
输出
复杂性
相关问题 更多 >
编程相关推荐