Python对象列表,获取属性的所有“方向”

我有一个对象列表(矩形).每个对象都有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对象列表,获取属性的所有“方向” - 代码日志