Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.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 3.x Python-如何对列表进行特殊排序_Python 3.x - Fatal编程技术网

Python 3.x Python-如何对列表进行特殊排序

Python 3.x Python-如何对列表进行特殊排序,python-3.x,Python 3.x,有人能告诉我如何按列“年龄”对数组进行排序吗 student = { 0 : {'name' : 'jane', 'age' : 40}, 1 : {'name' : 'pool', 'age' : 11}, 2 : {'name' : 'dave', 'age' : 28} } print(student[0]) print(student[1]) print(student[2]) 结果屏幕 {'name': 'jane', 'age': 40} {'nam

有人能告诉我如何按列“年龄”对数组进行排序吗

student = {
     0 : {'name' : 'jane', 'age' : 40},
     1 : {'name' : 'pool', 'age' : 11},
     2 : {'name' : 'dave', 'age' : 28}
}

print(student[0])
print(student[1])
print(student[2])
结果屏幕

{'name': 'jane', 'age': 40}
{'name': 'pool', 'age': 11}
{'name': 'dave', 'age': 28}
{'name': 'pool', 'age': 11}    
{'name': 'dave', 'age': 28}
{'name': 'jane', 'age': 40}
我试过了

student = sorted(student, key=lambda student: student[2]) # sort by age not work
但它并没有什么作用:-( 谢谢你的帮助

--编辑-- 正确的排序列表(排序期限)

结果屏幕

{'name': 'jane', 'age': 40}
{'name': 'pool', 'age': 11}
{'name': 'dave', 'age': 28}
{'name': 'pool', 'age': 11}    
{'name': 'dave', 'age': 28}
{'name': 'jane', 'age': 40}

这些都是
dict
s,而不是
list
s,因此它们没有顺序;对于内部
dict
s,它们没有数字键,因此对它们进行索引是错误的。也就是说,您可以将外部
dict
转换为排序的
list
,以获得所需的结果:

from operator import itemgetter

students = {
    0: {'name': 'jane', 'age': 40},
    1: {'name': 'pool', 'age': 11},
    2: {'name': 'dave', 'age': 28}
}

# Sort the sub-dicts by age and print
for student in sorted(students.values(), key=itemgetter('age')):
    print(student)

注意:由于子目录dicts也是无序的,因此不能保证每个学生的输出中,
name
出现在
age
之前。但这将以正确的顺序输出学生。

您这里有一本词典,词典是一个无序的结构。请编辑您的帖子a显示您希望如何查看输出。您期望的确切结果是什么?一个单一列表:
['aaa',0',ccc',1',bbb',2]
?两个不同的列表:
['aaa',ccc',bbb']
[0,1,2]
?成对的列表
[('aaa',0),('ccc',1),('bbb',2)]
?还有别的吗?我想你忘了一个等号,即
pole['txt']['aaa',ccc',bbb']
应该是
pole['txt']=['aaa',ccc',bbb']
pole['num']也一样
。我说得对吗?影子游侠:谢谢,我不想打印,我只是想调整一下!@SatNet:好吧,你可以将
排序的结果存储回学生的名字
中(那时它将是
目录的
目录,而不是
目录的
目录)如果您需要更改顺序,但还不需要打印。ShadowRanger:student=sorted(student.values(),key=itemgetter('age');对吗?谢谢。是的。尽管我可能会将其命名为
sortedstudents
或只是替换原始的
student
(除非
student
中的键有意义,例如学生ID号)。如果有意义,您可能希望实际编写一个适当的类来代表学生,而不是使用
dict
集合作为特殊的组织结构。ShadowRanger:您建议我如何将数据添加到列表中?