问题陈述:
在给定等价关系的情况下创建所有可能排列的多个列表(例如比较 y 坐标并忽略 x 坐标):
解决方案:
这是解决问题的一些工作代码:
from operator import itemgetter
from itertools import groupby, product, permutations, chain
points = [(1., 1.), (3., 0.),(-1., -1.) , (9., 2.), (-4., 2.) ]
points.sort(key=itemgetter(1))
groups = [list(permutations(g)) for k, g in groupby(points, itemgetter(1))]
for t in product(*groups):
print(list(chain.from_iterable(t)))
最后结果:
[(-1.0, -1.0), (3.0, 0.0), (1.0, 1.0), (9.0, 2.0), (-4.0, 2.0)]
[(-1.0, -1.0), (3.0, 0.0), (1.0, 1.0), (-4.0, 2.0), (9.0, 2.0)]
解释:
一步步:
1) 按 y 坐标对点进行排序,忽略 x 坐标:
>>> points = [(1., 1.), (3., 0.),(-1., -1.) , (9., 2.), (-4., 2.)]
>>> points.sort(key=itemgetter(1))
>>> points
[(-1.0, -1.0), (3.0, 0.0), (1.0, 1.0), (9.0, 2.0), (-4.0, 2.0)]
>>> ^-----------^-----------^-----------^-------------^ ascending y-values
2) 创建具有相同 y 坐标的点组:
>>> pprint([list(g) for k, g in groupby(points, itemgetter(1))], width=40)
[[(-1.0, -1.0)], # y = -1.0
[(3.0, 0.0)], # y = 0.0
[(1.0, 1.0)], # y = 1.0
[(9.0, 2.0), (-4.0, 2.0)]] # y = 2.0
3) 生成具有相同 y 坐标的点的所有排列:
>>> groups = [list(permutations(g)) for k, g in groupby(points, itemgetter(1))]
>>> pprint(groups)
[[((-1.0, -1.0),)], # y = -1.0
[((3.0, 0.0),)], # y = 0.0
[((1.0, 1.0),)], # y = 1.0
[((9.0, 2.0), (-4.0, 2.0)), ((-4.0, 2.0), (9.0, 2.0))]] # y = 2.0
4) 使用每个排列组中的一个元素创建所有可能的序列:
>>> for t in product(*groups):
print(t)
(((-1.0, -1.0),), ((3.0, 0.0),), ((1.0, 1.0),), ((9.0, 2.0), (-4.0, 2.0)))
(((-1.0, -1.0),), ((3.0, 0.0),), ((1.0, 1.0),), ((-4.0, 2.0), (9.0, 2.0)))
5)将每个子序列组合成一个列表:
>>> for t in product(*groups):
list(chain.from_iterable(t))
[(-1.0, -1.0), (3.0, 0.0), (1.0, 1.0), (9.0, 2.0), (-4.0, 2.0)]
[(-1.0, -1.0), (3.0, 0.0), (1.0, 1.0), (-4.0, 2.0), (9.0, 2.0)]