我有一个从另一种语言移植的功能,你能帮我把它变成“pythonic”吗?
这里以“非pythonic”方式移植的函数(这是一个人为的例子 - 每个任务都与一个项目或“无”相关联,我们需要一个不同项目的列表,不同的意思是没有重复的 .identifier属性,从任务列表开始):
@staticmethod
def get_projects_of_tasks(task_list):
projects = []
project_identifiers_seen = {}
for task in task_list:
project = task.project
if project is None:
continue
project_identifier = project.identifier
if project_identifiers_seen.has_key(project_identifier):
continue
project_identifiers_seen[project_identifier] = True
projects.append(project)
return projects
我什至还没有特别开始使它“pythonic”不要从错误的脚开始(例如列表理解与“如果project.identifier不是None,filter()基于谓词查找基于字典的标识符注册表,使用 set() 去除重复项等)
编辑:
根据反馈,我有这个:
@staticmethod
def get_projects_of_tasks(task_list):
projects = []
project_identifiers_seen = set()
for task in task_list:
project = task.project
if project is None:
continue
project_identifier = project.identifier
if project_identifier in project_identifiers_seen:
continue
project_identifiers_seen.add(project_identifier)
projects.append(project)
return projects