gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:29:56 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com