我有一个嵌套列表,我希望按内部和外部元素排序。我已经在stackoverflow上查看了其他解决方案并尝试了几个,但它们都没有按我希望的方式工作。下面,我提出了四次不起作用的尝试。每个代码块的注释都说明了我正在做什么以及我想要完成什么。
from operator import itemgetter
# a representation of my real data to be sorted
list_1 = [['key_e', ['v4eee', 'v1eee', 'v3eee', 'v2eee']], ['key_d', ['v4ddd', 'v1ddd', 'v3ddd', 'v2ddd']], ['key_a', ['v4aaa', 'v1aaa', 'v3aaa', 'v2aaa']], ['key_c', ['v4ccc', 'v1ccc', 'v3ccc', 'v2ccc']], ['key_b', ['v4bbb', 'v1bbb', 'v3bbb', 'v2bbb']]]
"""
# same data as above but formatted for readability
list_1 =
[
['key_e', ['v4eee', 'v1eee', 'v3eee', 'v2eee']],
['key_d', ['v4ddd', 'v1ddd', 'v3ddd', 'v2ddd']],
['key_a', ['v4aaa', 'v1aaa', 'v3aaa', 'v2aaa']],
['key_c', ['v4ccc', 'v1ccc', 'v3ccc', 'v2ccc']],
['key_b', ['v4bbb', 'v1bbb', 'v3bbb', 'v2bbb']]
]
"""
# when running the code, pick 1 of the 4 below sort methods and comment out the other 3
# sort method #1 that doesn't work the way I want it to
list_1.sort(key = lambda x: x[1])
list_1.sort(key = itemgetter(0))
"""
# sort method #2 that doesn't work the way I want it to
list_1 = sorted(list_1, key = lambda x: (x[0], x[1]))
"""
"""
# sort method #3 that doesn't work the way I want it to
list_1.sort(key = itemgetter(1))
list_1.sort(key = itemgetter(0))
"""
"""
# sort method #4 that doesn't work the way I want it to
list_1.sort(key = itemgetter(0, 1))
"""
# print the sorted data
for d in list_1:
print d[0] + ',' + d[1][0] + ',' + d[1][1] + ',' + d[1][2] + ',' + d[1][3] + '\r\n'
"""
# what I get using any of the sort methods
key_a,v4aaa,v1aaa,v3aaa,v2aaa
key_b,v4bbb,v1bbb,v3bbb,v2bbb
key_c,v4ccc,v1ccc,v3ccc,v2ccc
key_d,v4ddd,v1ddd,v3ddd,v2ddd
key_e,v4eee,v1eee,v3eee,v2eee
# what I want
key_a,v1aaa,v2aaa,v3aaa,v4aaa
key_b,v1bbb,v2bbb,v3bbb,v4bbb
key_c,v1ccc,v2ccc,v3ccc,v4ccc
key_d,v1ddd,v2ddd,v3ddd,v4ddd
key_e,v1eee,v2eee,v3eee,v4eee
"""
答案 0 :(得分:2)
我认为您希望对子列表进行排序,并对要排序的外部列表进行排序。在这种情况下,分两步完成:
sorted_inner = [[k, sorted(l)] for k, l in list_1]
sorted_outer = sorted(sorted_inner)
这给了我:
sorted_outer == [['key_a', ['v1aaa', 'v2aaa', 'v3aaa', 'v4aaa']],
['key_b', ['v1bbb', 'v2bbb', 'v3bbb', 'v4bbb']],
['key_c', ['v1ccc', 'v2ccc', 'v3ccc', 'v4ccc']],
['key_d', ['v1ddd', 'v2ddd', 'v3ddd', 'v4ddd']],
['key_e', ['v1eee', 'v2eee', 'v3eee', 'v4eee']]]