我有一个对象列表(矩形)。每个对象都有 2 个属性(高度和宽度)。我想获得此列表的所有“方向”(不确定如何准确调用它),因此(可能)交换矩形的高度和宽度的所有 2^n(对于 n 个矩形的列表)方向.对于 3 个对象的列表,它看起来像这样(顺序不重要):
[R1(w, h), R2(w2, h2), R3(w3, h3)]
[R1(w, h), R2(w2, h2), R3(h3, w3)]
[R1(w, h), R2(h2, w2), R3(w3, h3)]
[R1(w, h), R2(h2, w2), R3(h3, w3)]
[R1(h, w), R2(w2, h2), R3(w3, h3)]
[R1(h, w), R2(w2, h2), R3(h3, w3)]
[R1(h, w), R2(h2, w2), R3(w3, h3)]
[R1(h, w), R2(h2, w2), R3(h3, w3)]
我的矩形类看起来像这样:
class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width
def place(self):
"""Method to place tile in a larger grid"""
def remove(self):
"""Method to remove tile from larger grid"""
有没有简单的方法来做到这一点?
最佳答案
准备:
class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width
def flipped(self):
return Rectangle(self.width, self.height)
def __repr__(self):
return 'Rectangle({}, {})'.format(self.height, self.width)
rectangles = [Rectangle(1, 10), Rectangle(2, 20), Rectangle(3, 30)]
解决方法:
from itertools import product
for orientation in product(*zip(rectangles, map(Rectangle.flipped, rectangles))):
print(orientation)
输出:
(Rectangle(1, 10), Rectangle(2, 20), Rectangle(3, 30))
(Rectangle(1, 10), Rectangle(2, 20), Rectangle(30, 3))
(Rectangle(1, 10), Rectangle(20, 2), Rectangle(3, 30))
(Rectangle(1, 10), Rectangle(20, 2), Rectangle(30, 3))
(Rectangle(10, 1), Rectangle(2, 20), Rectangle(3, 30))
(Rectangle(10, 1), Rectangle(2, 20), Rectangle(30, 3))
(Rectangle(10, 1), Rectangle(20, 2), Rectangle(3, 30))
(Rectangle(10, 1), Rectangle(20, 2), Rectangle(30, 3))
关于Python对象列表,获取属性的所有 'orientations',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29988288/