python - How to return with a python method A NEW class object?
问题描述
I have some questions with respect to the not working code below:
- How to make a method search return a New Database object?
- Can
__init__
take as an argument a schema and alist
(which is alist
of dictionaries - where I do my search)? - How to avoid writing similar function in search method again and again, cause there are a lot of field names in the database.
Thanks in advance for your help.
class DataBase():
# Searches Movies by title and gives its entire info :( (stupid)
def __init__(self, movies, schema):
pass
def search(self, field_name, field_value1, field_value2=None):
if field_name=='title':
mov=[]
for movie in movies:
if field_value1 == movie['movie_title']:
mov.append(movie)
return mov
if field_name=='year':
for movie in movies:
if field_value2:
if movie['title_year'] in range (field_value1, field_value2+1):
return movie['movie_title'],movie['title_year']
else:
if movie['title_year']==field_value1:
return movie['movie_title'],movie['title_year']
if field_name=='actor_1_name':
mov=[]
for movie in movies:
if field_value1 == movie['actor_1_name']:
mov.append(movie)
return mov
**strong text**
解决方案
目前还不清楚您要做什么,如果没有输入示例和所需结果的示例,很难解释,但这可能很接近。
class DataBase():
def __init__(self, movies, schema):
self.movies = movies
self.schema = schema
def search(self, field_name, field_value1, field_value2=None):
search_result = []
for movie in self.movies:
if field_value2:
if movie[field_name] in range((field_value1, field_value2+1)):
search_results.append(movie)
else:
if movie[field_name] == field_value1:
search_results.append(movie)
return DataBase(search_results, self.schema)
您甚至可能希望简化搜索中的比较。您可以为(两种)不同类型的比较定义辅助函数;根据参数选择要使用的比较;然后在搜索中使用所选功能。
...
def search(self, field_name, field_value1, field_value2=None):
# comparison types
def range_comparison(movie, start=field_value1, end=field_value2):
return movie[field_name] in range(start, end+1)
def equality_comparison(movie, name=field_value1):
return movie[field_name] == name
# which comparison to use
comparison = range_comparison if field_value2 else equality_comparison
search_result = []
for movie in self.movies:
if comparison(movie):
search_results.append(movie)
# or
# search_results = [movie for movie in movies if comparison(movie)]
return DataBase(search_results, self.schema)
出于某种原因,这对我很有吸引力,因为它将比较类型的逻辑与实际搜索分开。
它不考虑为search_results
空 - 没有找到电影。
推荐阅读
- java - 如何在 Elasticsearch 中管理值的自动排序
- c++ - const_iterator 的 ++ 运算符如何用于向量
在 C++ 标准库中? - python - 如何使用 H2o 库获取 GBM 模型上的数据
- flutter - 在 Flutter DropdownButtonFormField 中获取多个值
- c++ - 为什么 fftw 在 vscode 中总是未定义的引用?
- docker - Docker - 无论框架如何设置多个项目(在 php 上)
- c# - Shaded pictures on focused item in collection view
- python - 最多 X 个值的平均值,然后与最后一个值取平均值?
- c# - linq: from object in an object to just an object
- javascript - 如何使用 Chart.js 创建这样的条形图?