[英]list of lists that splits on change between positive and negative values
Every time the item in a list changes from a positive to negative value, start a new sub-list. 每当列表中的项目从正值变为负值时,就启动一个新的子列表。 For the data:
对于数据:
khanh = [-2.22,1.4,2,3,4,5,6,0,-2,-3,-4,-5,7,8,9]
I'm trying to output: 我正在尝试输出:
[[-2.22],[1.4,2,3,4,5,6,0],[-2,-3,-4,-5],[7,8,9]]
My code so far: 到目前为止,我的代码:
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)
>>> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.