如何简化python中的重复列表推导?

时间:2014-02-04 10:38:43

标签: python syntax refactoring list-comprehension

此代码计算包含输入矩形列表的最小矩形:

left = min(x.left for x in rect)
bottom = min(x.bottom for x in rect)
right = max(x.right for x in rect)
top = max(x.top for x in rect)

我确信这可以简化为单行声明但老实说我不知道​​如何。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

这里不要使用生成器表达式,只需循环一次,一次更新minimi和maximi:

left = bottom = float('inf')
right = top = float('-inf')
for x in rect:
    if x.left < left:     left = x.left
    if x.bottom < bottom: bottom = x.bottom
    if x.right > right:   right = x.right
    if x.top > top:       top = x.top

是的,这更详细,但效率更高it越长,与4个生成器表达式相比,上述循环执行的工作就越少。

您可以生成结果的词典

minimi = dict.fromkeys(('left', 'bottom'), float('inf'))
maximi = dict.fromkeys(('right', 'top'), float('-inf'))
for x in rect:
    for key in minimi:
        if getattr(x, key) < minimi[key]: minimi[key] = getattr(x, key)
    for key in maximi:
        if getattr(x, key) > maximi[key]: maximi[key] = getattr(x, key)

但这几乎不值得抽象,而不是每个2个值。

答案 1 :(得分:0)

你可以通过减少来解决问题,但它的效率可能低于Martijn Pieters的建议。

from functools import reduce

def fn(current_mins_maxs, r):
    z = zip(current_mins_maxs, (r.left, r.bottom, r.right, r.top))
    return [min(z[0]), min(z[1]), max(z[2]), max(z[3])]

first, rest = rectangles[0], rectangles[1:]
# Or, if you are using Python 3, you can write:
# first, *rest = rectangles
mins_and_maxs = reduce(fn, rest, (first.left, first.bottom, first.right, first.top))