在正值和负值之间进行分组的列表列表

时间:2018-02-24 19:52:44

标签: python python-3.x

每次列表中的项目从正值变为负值时,都会启动一个新的子列表。对于数据:

khanh = [-2.22,1.4,2,3,4,5,6,0,-2,-3,-4,-5,7,8,9]

我正在尝试输出:

[[-2.22],[1.4,2,3,4,5,6,0],[-2,-3,-4,-5],[7,8,9]]

到目前为止我的代码:

adam = [[prev, next] for prev, next in zip(khanh, khanh[1:]+[None])]

amber = [[currentIdx,
          khanh[idx + 1] if idx < len(khanh) - 1 else None] for idx, currentIdx in enumerate(khanh)]

robby = [x for x in khanh if x > 0 ]

print(amber)
print()
print(adam)

1 个答案:

答案 0 :(得分:2)

>>> lst = [-2.22,1.4,2,3,4,5,6,0,-2,-3,-4,-5,7,8,9]
>>> correct = [[-2.22],[1.4,2,3,4,5,6,0],[-2,-3,-4,-5],[7,8,9]]
>>> from itertools import groupby
>>> result = [list(g) for _, g in groupby(lst, key=lambda a: a < 0)]
>>> correct == result
True