我从您之前的问题中引用了@jamylak 的答案,并显示了一些细微的修改。
虽然您可以尝试将结果的模式与您的 匹配x
,y
但您也可以修改原始解决方案以将 x 和 y 视为点 (x,y):
from itertools import groupby
x = [0,1,2,3,4,3,2,3,-2,-4,-7,2,2]
y = [0,1,2,3,4,5,6,7,8,9,10,11,12]
def slope(a,b): #Returns 1 for inc, 0 for equal and -1 for dec
return (a > b) - (a < b)
def groups(nums):
#
# Change the call to slope() to assume 2d point tuples as values
#
for k,v in groupby(zip(nums,nums[1:]), lambda (x,y): slope(x[0],y[0])):
yield next(v) + tuple(y for x,y in v)
#
# Pass in a zipped data structure
#
print list(groups(zip(x,y)))
# result
[((0, 0), (1, 1), (2, 2), (3, 3), (4, 4)),
((4, 4), (3, 5), (2, 6)),
((2, 6), (3, 7)),
((3, 7), (-2, 8), (-4, 9), (-7, 10)),
((-7, 10), (2, 11)),
((2, 11), (2, 12))]
虽然我不确定生成的格式是否适合您。
以下是如何将它们分开:
from operator import itemgetter
result = list(groups(zip(x,y)))
x = [map(itemgetter(0), points) for points in result]
y = [map(itemgetter(1), points) for points in result]
print x
# [[0, 1, 2, 3, 4], [4, 3, 2], [2, 3], [3, -2, -4, -7], [-7, 2], [2, 2]]
print y
# [[0, 1, 2, 3, 4], [4, 5, 6], [6, 7], [7, 8, 9, 10], [10, 11], [11, 12]]
或者按照@jamylak 的建议:
x,y = zip(*[zip(*points) for points in result])
为了说明@jamylak 所说的内容,关于对groups()
方法的修改如何允许 N 维点或数据集:
z = ['foo',1,2,'bar',4,5,6,'foo',8,9,10,'bar',12]
print list(groups(zip(x,y,z)))
# result
[((0, 0, 'foo'), (1, 1, 1), (2, 2, 2), (3, 3, 'bar'), (4, 4, 4)),
((4, 4, 4), (3, 5, 5), (2, 6, 6)),
((2, 6, 6), (3, 7, 'foo')),
((3, 7, 'foo'), (-2, 8, 8), (-4, 9, 9), (-7, 10, 10)),
((-7, 10, 10), (2, 11, 'bar')),
((2, 11, 'bar'), (2, 12, 12))]
您可以看到它可以是任意数据集,并且它总是只对每个数据集的第一个元素进行分组。