要获得更干净的代码,应该考虑使用类来封装数据。你知道吗
让我们看看:class Person(object):
def __init__(self, identifier, firstname, name, state):
self.id = identifier
self.firstname = firstname
self.name = name
self.state = state
def __repr__(self):
return "".format(self.firstname, self.name, self.id, self.state)
def as_list(self):
return [self.firstname, self.name, self.state]
class PersonList(list):
def __init__(self, *args, **kwargs):
list.__init__(self, *args, **kwargs)
def getById(self, identifier):
""" return the person of this list whose the id is equals to the requested identifier. """
# filter(boolean function, iterable collection) -> return a collection hat contain only element that are true according to the function.
# here it is used a lambda function, a inline function declaration that say for any given object x, it return x.id == identifier.
# the list is filtered to only get element with attribut id equals to identifier. See https://docs.python.org/3.4/library/functions.html#filter
tmp = list(filter(lambda x: x.id == identifier, self))
if len(tmp)==0:
raise Exception('Searched for a Person whose id is {0}, but no one have this id.'.format(identifier))
elif len(tmp) > 1:
raise Exception('Searched for a Person whose id is {0}, and many people seem to share this id. id are supposed to be unique.'.format(identifier))
return tmp[0]
##CONSTANTS##
#id list - modified to not instanciate 9 Person
ids = [[1412,2521,3411],#bob, jane, jim
[3411,1412,1412],#jim, bob, bob
[3411,2521,2521]]#jim, jane, jane
#person list
index=PersonList([Person(1412, 'Bob', 'Smith', 'Ohio'),
Person(2521, 'Jane', 'Doe', 'Texas'),
Person(3411, 'Jim', 'Black', 'New York')])
def computeResult(id_list, personList):
personList = [ [personList.getById(identifier) for identifier in subList] for subList in id_list]
resultList= []
for sublist in personList:
tmp = []
for person in sublist:
tmp += person.as_list()
resultList.append(tmp)
return resultList
if __name__ == "__main__":
print(computeResult(ids, index))
因为我的观点是,你用一只手上的数据结构是错误的。应用程序应该处理Person对象之类的事情,而不是字符串列表。反正是你的应用程序。我只是建议您考虑使用personList作为处理数据的更好的数据结构,而不是这个丑陋的列表。
另一方面,如果id像我想的那样是唯一的,如果您成功地将数据放入字典中,例如index={1412 : Person(...), 2500 : Person(...), ...}
或者index={1412: ['Bob', 'Doe', ...], 2500 : [...], ...}`
它确实更实用,因为您可以删除PersonList类,然后仅使用index.get(1412)来获取与id对应的数据
编辑:根据请求添加跟踪示例。你知道吗
此脚本保存在名为“”的文件中柔软的““python3
>>> import sof
>>> sof.index
[, , ]
>>> sof.index.getById(666)
Traceback (most recent call last):
File "", line 1, in
File "/home/vaisse/Bureau/sof.py", line 25, in getById
raise Exception('Searched for a Person whose id is {0}, but no one have this id.'.format(identifier))
Exception: Searched for a Person whose id is 666, but no one have this id.
如你所见,一旦出错,一切都会停止。如果这种行为不是您想要的,您还可以返回一个None值,并在某个地方跟踪失败的内容,而不是增加一个Exception,然后继续处理数据。如果你想让你的应用程序在出错的情况下仍然运行,你应该看看https://docs.python.org/3.1/library/warnings.html。否则,提出一个简单的例外就足够了