Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用另一个列表更改对象列表的顺序_Python - Fatal编程技术网

Python 用另一个列表更改对象列表的顺序

Python 用另一个列表更改对象列表的顺序,python,Python,这与尝试从另一个列表对列表重新排序的其他帖子类似,但这是尝试从对象列表的属性进行排序列表a的编号为1-5,测试列表对象列表的属性也为1-5。我想按照list\u a中的顺序重新排列这些列表属性。这是我的代码,请帮助: class tests(): def __init__(self,grade): self.grade = grade test_list = [] for x in range(1,6): test_object = tests(x)

这与尝试从另一个列表对列表重新排序的其他帖子类似,但这是尝试从对象列表的属性进行排序<代码>列表a的编号为1-5,测试列表对象列表的属性也为1-5。我想按照
list\u 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)

您可以定义合适的键并使用字典作为键函数:

输出:

# before
1  2  3  4  5  

# after
5  3  2  1  4 

您可以定义合适的键并使用字典作为键函数:

输出:

# before
1  2  3  4  5  

# after
5  3  2  1  4 

您可以根据字典查找进行如下操作:

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]

您可以根据字典查找进行如下操作:

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]

欢迎来到StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。欢迎使用StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。