简体   繁体   English

重构此列表构建代码的最Pythonic方法是什么?

[英]What's the most Pythonic way to refactor this list building code?

I have a list of results that I need to pull out various other lists from. 我有一个结果列表,需要从中提取其他各种列表。 For example, all owners that are male, all cars between 5 and 10 years old. 例如,所有车主均为男性,所有汽车的年龄在5至10岁之间。

def get_male_owners(self):
    results = []
    for result in self.results:
        if result.owner.sex.male:
            results.append(result)
    return results

def get_cars_5_to_10(self):
    results = []
    for result in self.results:
        if result.car:
            if self.is_5_to_10(result.car):
                results.append(result)
    return results

def is_5_to_10(self, car):
    if car.age <= 10 and car.age >= 5:
        return True
    else:
        return False

The thing is there will be lots of different lists I need to build, but a lot of the code in each of the list building functions is common. 问题是,我需要构建许多不同的列表,但是每个列表构建功能中的很多代码是通用的。 What's the best way to implement DRY in a Pythonic way here? 在这里以Python方式实现DRY的最佳方法是什么? Thanks. 谢谢。

Use list comprehensions: 使用清单的理解:

def get_male_owners(self):
    return [res for res in self.results if res.owner.sex.male]

def get_cards_5_to_10(self):
    return [res for res in self.results if res.car and self.is_5_to_10(res.car)]

def is_5_to_10(self, car):
    return 5 <= car.age <= 10

If you just need something iterable you could also return a generator expression by replacing the brackets with parentheses. 如果只需要可迭代的内容,也可以通过用括号替换括号来返回生成器表达式。

And yes, the x <= y <= z expression does work in python and it does yield the correct result and not something like (5 <= car.age) <= 10 . 是的, x <= y <= z表达式确实在python中工作,并且确实产生正确的结果,而不是(5 <= car.age) <= 10

def filter(self, by=None):
    return [res for res in self.results if by(res)]

def get_male_owners(self):
    return self.filter(lambda res: res.owner.sex.male)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM