我想在项目超过一定长度的点拆分列表。
我的数据的简化版本是:
li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300]
我试图达到的结果如下
new_li = [[1,2,3],[4000,5,6,7,8],[9000,10,11,12,1300]]
我是编程新手,对解决这个问题的方法有点困惑。
我正在考虑在每次项目长度大于 2 时循环并创建一个索引,但我不知道如何重新创建嵌套列表。
像这样的东西:
li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300]
r = [[]] # start with a list containing an empty sub-list
for i in li:
if i >= 2000:
# start a new sub-list when we see a big value
r.append([i])
else:
# append to the last sub-list of r
r[-1].append(i)
from itertools import groupby
li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300]
class GroupbyHelper(object):
def __init__(self, val):
self.val = val
self.i = 0
def __call__(self, val):
self.i += (val > self.val)
return self.i
>>> [list(g) for k, g in groupby(li, key=GroupbyHelper(2000))]
[[1, 2, 3], [4000, 5, 6, 7, 8], [9000, 10, 11, 12, 1300]]
使用切片而不是重新附加每个项目可能更有效:
li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300]
res = []
indices = (i for i, v in enumerate(li) if v > 2000)
i = 0
for i2 in indices:
res.append(li[i:i2])
i = i2
res.append(li[i:])
更短的版本:
li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300]
indices = [i for i, v in enumerate(li) if v > 2000]
res = [li[i:j] for i, j in zip([0]+indices, indices+[None])]