我正在处理学生数据,主要想做两件事。虽然我的实现可以工作,但随着数组的增长,它们往往会变得很慢:
students = [{'studentid':1001,'name':'Erick','classRoom':'SA9','ranking':23},{'studentid':1009,'name':'James','classRoom':'SA1','ranking':1}]我想通过id来获取一个学生:
def get_student(id):
global students
for student in students:
if student['studentid'] == id:
return student
return False
def update_student_rank(id, rank):
student = get_students(id)
if student:
student.ranking = rank
return student
return False任务很大程度上是找到一个特定的学生并对该特定的学生进行操作。当数组变大时,我注意到它确实变慢了,我想知道是否有更快的方法来找到特定的学生?
发布于 2020-04-02 07:58:55
也许你可以试试这个:
students = [{'studentid':1001,'name':'Erick','classRoom':'SA9','ranking':23},{'studentid':1009,'name':'James','classRoom':'SA1','ranking':1}] # Original
# Pre-pocessing takes O(n)
id_lookup = dict()
for student in students:
id_lookup[student['studentid']] = student # Assume no collision i.e. studentid is unique
# Lookup O(1)
print (id_lookup[1001])
# {'studentid': 1001, 'name': 'Erick', 'classRoom': 'SA9', 'ranking': 23}做update_student_rank也很简单,因为你只需要用student = id_lookup[id]替换student = get_students(id)即可。(需要全局变量。)
https://stackoverflow.com/questions/60981865
复制相似问题