假设有一个由对象组成的数组以及一个参考数组,需要根据参考数组中元素的顺序对对象数组进行排序,步骤如下:
reference_array = list(set(reference_array))
for obj in obj_array:
obj.index = reference_array.index(obj.name) + 1
sorted_array = sorted(obj_array, key=lambda obj: obj.index)
完整代码示例:
# define class for object
class Obj(object):
def __init__(self, name):
self.name = name
# initialize object and reference arrays
obj_array = [Obj('B'), Obj('C'), Obj('D'), Obj('A')]
reference_array = ['A', 'B', 'C', 'D', 'A']
# remove duplicates from reference array
reference_array = list(set(reference_array))
# add index to each object based on reference array
for obj in obj_array:
obj.index = reference_array.index(obj.name) + 1
# sort object array based on index
sorted_array = sorted(obj_array, key=lambda obj: obj.index)
# print sorted object array
for obj in sorted_array:
print(obj.name)