Python 如何按条件将列表拆分为列表?
我想根据条件将一个列表拆分为多个列表。如果序列中的差异增长超过4,则触发将列表从上次拆分的项目拆分到该项目 例如:Python 如何按条件将列表拆分为列表?,python,Python,我想根据条件将一个列表拆分为多个列表。如果序列中的差异增长超过4,则触发将列表从上次拆分的项目拆分到该项目 例如: in = [1,2,3,9,10,11,100,200] out = [ [1,2,3 ], [ 9,10,11 ], [100], [200] ] 按条件 If (next - prev) > 4 注意:in和next分别是Python关键字和内置函数 诀窍是将zip()函数用于相同列表的两个片段,但在一个项目上移动: in_list = [1, 2, 3, 9, 1
in = [1,2,3,9,10,11,100,200]
out = [ [1,2,3 ], [ 9,10,11 ], [100], [200] ]
按条件
If (next - prev) > 4
注意:in和next分别是Python关键字和内置函数
诀窍是将zip()
函数用于相同列表的两个片段,但在一个项目上移动:
in_list = [1, 2, 3, 9, 10, 11, 100, 200]
parts = [[]]
for prev_item, next_item in zip(in_list[:-1], in_list[1:]):
top = parts[-1]
top.append(prev_item)
if next_item - prev_item > 4:
parts.append([])
top = parts[-1]
top.append(in_list[-1])
输出为:
[[1, 2, 3], [9, 10, 11], [100], [200]]
使用
numpy
模块的简短解决方案:
import numpy as np
arr = np.array([1,2,3,9,10,11,100,200])
out = [a.tolist() for a in np.split(arr, np.where(np.diff(arr) > 4)[0]+1)]
print(out)
输出:
[[1, 2, 3], [9, 10, 11], [100], [200]]
-找到满足条件“下一个值和上一个值之间的差值大于4”的数组索引np.where(np.diff(arr)>4)
-按关键索引拆分初始数组np.split(x,索引)
- 可能的方法之一:
ls = [1,2,3,9,10,11,100,200, 201, 209]
#output list
output = list()
startind = 0
for ind, val in enumerate(ls):
if ls[ind]-ls[ind-1] > 4:
output.append(ls[startind:ind])
startind = ind
# appending the left over from last detected difference of 4
output.append(ls[startind:])
print output
输出:[[1,2,3],[9,10,11],[100],[200,201],[209]。您能展示您迄今为止的尝试吗?也许你真的离得很近,一双额外的眼睛可能会帮助你发现你正在犯的小错误?下一个和上一个应该是什么?这个条件是如何产生输出的?考虑到你的条件,人们会期望:
[…,[100],[200]]
不应该100
和200
在两个单独的列表中,因为200-100>4?喜欢numpy方法。
[[1, 2, 3], [9, 10, 11], [100], [200]]
ls = [1,2,3,9,10,11,100,200, 201, 209]
#output list
output = list()
startind = 0
for ind, val in enumerate(ls):
if ls[ind]-ls[ind-1] > 4:
output.append(ls[startind:ind])
startind = ind
# appending the left over from last detected difference of 4
output.append(ls[startind:])
print output