Optimized method of cutting/slicing sorted lists(优化的切割/切片排序列表的方法)
问题描述
在 Python 中是否有任何预制的优化工具/库来剪切/切片小于"值的列表?
Is there any pre-made optimized tool/library in Python to cut/slice lists for values "less than" something?
问题来了:假设我有一个类似的列表:
Here's the issue: Let's say I have a list like:
a=[1,3,5,7,9]
我想删除所有 <=
6 的数字,所以结果列表将是
and I want to delete all the numbers which are <=
6, so the resulting list would be
[7,9]
6 不在列表中,所以我不能使用列表的内置 index(6)
方法.我可以这样做:
6 is not in the list, so I can't use the built-in index(6)
method of the list. I can do things like:
#!/usr/bin/env python
a = [1, 3, 5, 7, 9]
cut=6
for i in range(len(a)-1, -2, -1):
if a[i] <= cut:
break
b = a[i+1:]
print "Cut list: %s" % b
如果要从中剪切的索引接近列表的末尾,这将是一种相当快捷的方法,但如果项目接近列表的开头(假设我想删除所有>2
的项目,会有很多迭代).
which would be fairly quick method if the index to cut from is close to the end of the list, but which will be inefficient if the item is close to the beginning of the list (let's say, I want to delete all the items which are >2
, there will be a lot of iterations).
我也可以使用二进制搜索等实现我自己的 find 方法,但我想知道是否有一个更广泛的内置库来处理我可以在其他情况下重用的此类事物(例如, 如果我需要删除所有 >=6
).
I can also implement my own find method using binary search or such, but I was wondering if there's a more... wide-scope built in library to handle this type of things that I could reuse in other cases (for instance, if I need to delete all the number which are >=6
).
提前谢谢你.
推荐答案
你可以使用 bisect 模块 执行排序搜索:
You can use the bisect module to perform a sorted search:
>>> import bisect
>>> a[bisect.bisect_left(a, 6):]
[7, 9]
这篇关于优化的切割/切片排序列表的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:优化的切割/切片排序列表的方法
基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01