这类似于试图从另一个列表重新排序列表的其他发布,但这是试图从对象列表的属性中进行。 list_a
的编号为1-5,而test_list对象列表也包含1-5的属性。我想将这些列表属性重新排列为list_a
中的顺序。这是我的代码,请帮助:
class tests():
def __init__(self,grade):
self.grade = grade
test_list = []
for x in range(1,6):
test_object = tests(x)
test_list.append(test_object)
for x in test_list:
print(x.grade)
list_a = [5,3,2,1,4]
for x in [test_list]:
test_list.append(sorted(x.grade,key=list_a.index))
print(test_list)
答案 0 :(得分:2)
您可以定义合适的键并将字典用作键功能:
class tests(): def __init__(self,grade): self.grade = grade test_list = [] for x in range(1,6): test_object = tests(x) test_list.append(test_object) for x in test_list: print(x.grade, end = " ") # modified print("") list_a = [5,3,2,1,4]
# works because unique values, if you had dupes, only the last occurence would
# be used for sorting
d_a = { val:pos for pos,val in enumerate(list_a,1)}
test_list.sort(key = lambda x: d_a[x.grade])
for x in test_list:
print(x.grade, end = " ")
输出:
# before
1 2 3 4 5
# after
5 3 2 1 4
答案 1 :(得分:0)
您可以执行以下操作以根据字典查找进行排序:
test_cache = {}
for test in test_list:
test_cache[test.grade] = test # store the object based on the test score
sorted_objects = []
for x in list_a:
sorted_objects.append(test_cache.get(x)) # build the output list based on the score
print [test.grade for test in sorted_objects]
输出:
[5, 3, 2, 1, 4]