![](/img/trans.png)
[英]What's the most idiomatic way in Java to dynamically call a function by name?
[英]What's the most Pythonic way to refactor this list building code?
我有一個結果列表,需要從中提取其他各種列表。 例如,所有車主均為男性,所有汽車的年齡在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
問題是,我需要構建許多不同的列表,但是每個列表構建功能中的很多代碼是通用的。 在這里以Python方式實現DRY的最佳方法是什么? 謝謝。
使用清單的理解:
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
如果只需要可迭代的內容,也可以通過用括號替換括號來返回生成器表達式。
是的, 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.