python – 查找列表中所有可能的子列表
发布时间:2021-01-11 13:12:10 所属栏目:Python 来源:互联网
导读:假设我有以下列表 [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18] 我想找到一个具有一定数量的可能的子列表,它们不包含一个数字,而不会丢失数字的顺序. 例如,所有可能的子列表,长度为6,没有12是: [1,2,3,4,5,6][2,3,4,5,6,7][3,4,5,6,7,8][4,5,6,7,8,9][5,
假设我有以下列表 [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18] 我想找到一个具有一定数量的可能的子列表,它们不包含一个数字,而不会丢失数字的顺序. 例如,所有可能的子列表,长度为6,没有12是: [1,6] [2,7] [3,8] [4,9] [5,10] [6,11] [13,18] 问题是我想在一个很大的列表中做,我想要最快捷的方式. 更新我的方法: oldlist = [1,18] newlist = [] length = 6 exclude = 12 for i in oldlist: if length+i>len(oldlist): break else: mylist.append(oldlist[i:(i+length)] for i in newlist: if exclude in i: newlist.remove(i) 我知道这不是最好的方法,所以我需要一个更好的方法. 解决方法一个简单的,非优化的解决方案将是result = [sublist for sublist in (lst[x:x+size] for x in range(len(lst) - size + 1)) if item not in sublist ] 优化版本: result = [] start = 0 while start < len(lst): try: end = lst.index(item,start + 1) except ValueError: end = len(lst) result.extend(lst[x+start:x+start+size] for x in range(end - start - size + 1)) start = end + 1 (编辑:台州站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- python – SQLAlchemy吃RAM
- python – Django的call_command失败,缺少必需的参数
- python – 如何在TensorFlow中实现递归神经网络?
- Python运算符重载用法实例分析
- python-2.7 – 无法安装PythonMagick Windows 7
- python – 确认import *和xxx导入之间的区别*
- django – Travis:“创建测试数据库时出错:创建数据库的权
- python – ImportError:Elastic Beanstalk中没有名为djang
- 如何生成字符之间带空格的字符串的所有可能组合?Python
- python源代码中的sys模块在哪里?