Python对象列表,获取属性的所有 'orientations'

标签 python list object attributes swap

我有一个对象列表(矩形)。每个对象都有 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/

相关文章:

python - 用 python 编写脚本语言

c# - 如何将 ienumerable 集合附加到 C# 中的现有列表

c# - 如何在 C# 中创建一个 List<int> 数组?

ios - Flutter - 如何删除单个 google_maps_flutter ^0.5.21 标记?

java - 从类名创建对象

python - 返回匿名类或对象用作 'struct' 更好吗?

python - CNN 喀拉斯 : ValueError: Negative dimension size caused by subtracting 3 from 2 for 'conv2d

python - ImportError : Missing required dependencies ['numpy' ]. 没有任何帮助

python - 将 .doc/.docx 转换为保留表格的文本

javascript - 对象和属性到底是什么?它们可以同时存在吗