def takeSection(sequence):
it = iter(sequence)
a = -1
group = []
while True:
try:
a, last = next(it), a
except StopIteration:
if group:
yield group
return
if a < 0 and last >= 0:
if group:
yield group
group = [a]
else:
group.append(a)
>>> sequence = [-2323, -2324, -53434, -1027, -34232, 343434, 5657, 6565, 6500, -343434, -3434, -565, 5845, 4667, 5453, 98356]
>>> list(takeSection(sequence))
Out[2]:
[[-2323, -2324, -53434, -1027, -34232, 343434, 5657, 6565, 6500],
[-343434, -3434, -565, 5845, 4667, 5453, 98356]]
编辑
如果您想在一对值中的第一个值上过滤它,您可以更改 if 条件来测试它。例如,您可以将条件行更改为if a[0] < 0 and last[0] >=0
,并且您还需要初始化a
为a = (-1, -1)
但是,我很想改用更通用和更有用的功能。
def sections(sequence, key):
it = iter(sequence)
a = placeholder = object()
group = []
while True:
try:
a, last = next(it), a
except StopIteration:
if group:
yield group
return
if last is not placeholder and key(a, last):
if group:
yield group
group = [a]
else:
group.append(a)
>>> sequence = [(-2323, -7465), (-2324, -7687), (-53434, -1027), (-34232, 343434), (5657, 6565), (6500, 978987), (-343434, -987), (-3434, -565), (-98, -8798), (-89898, -898), (5845, 4667), (5453, 98356)]
>>> list(sections(sequence, key=lambda current, last: current[0] < 0 and last[0] >= 0))
Out[1]:
[[(-2323, -7465), (-2324, -7687), (-53434, -1027), (-34232, 343434), (5657, 6565), (6500, 978987)],
[(-343434, -987), (-3434, -565), (-98, -8798), (-89898, -898), (5845, 4667), (5453, 98356)]]