[英]Sort by elements in multiple layers of multi-layered tuple - Python
I have a tuple of tuples of tuples and I want to sort it first by the second element, then first, then third of the lowermost layer and iteratively do this for each tuple of the middle layer. 我有一个元组元组的元组,我想先用第二个元素对它进行排序,然后是第一个,然后是最下层的第三个,并迭代地为中间层的每个元组执行此操作。
For example, I want to sort the following list: 例如,我想对以下列表进行排序:
sampleToBeSorted = (
(('D', 52, 'B'), ('D', 32, 'B')),
(('D', 31, 'A'), ('D', 52, 'B')),
(('A', 31, 'B'), ('D', 32, 'B')),
(('C', 31, 'A'), ('B', 24, 'C'), ('C', 33, 'B')),
(('D', 31, 'A'), ('D', 32, 'B'), ('C', 29, 'B'), ('D', 216, 'C')),
(('D', 40, 'B'), ('A', 32, 'C')),
)
such that it looks like this: 它看起来像这样:
sampleToBeSorted = (
((‘A’, 31, ‘B’), (‘D’, 32, ‘B’)),
((‘C’, 31, ‘A’), (‘B’, 24, ‘C’), (‘C’, 33, ‘B’)),
((‘D’, 31, ‘A’), (‘D’, 32, ‘B’), (‘C’, 29, ‘B’), (‘D’, 216, ‘C’)),
((‘D’, 31, ‘A’), (‘D’, 52, ‘B’)),
((‘D’, 40, ‘B’), (‘A’, 32, ‘C’)),
((‘D’, 52, ‘B’), (‘D’, 32, ‘B’)),
)
I've gotten part way there, using: 我已经分道扬with,使用:
sortedSample = sorted(sampleToBeSorted, key= lambda x:(x[0][1],x[0][0],x[0][2]))
But this only sorts over the first tuple in the middle layer. 但这只能在中间层的第一个元组中进行排序。 To get it to iteratively do this for all of the tuples in the middle layer, I think I can just modify this to something like
为了让它迭代地为中间层的所有元组执行此操作,我想我可以将其修改为类似
sortedSample = sorted(sampleToBeSorted, key= lambda x:(x[i][1],x[i][0],x[i][2]) for i in range(len(sampleToBeSorted[x]))
This is invalid syntax and I can't quite figure out what the right way to write this would be. 这是无效的语法,我无法弄清楚写这个的正确方法是什么。 Any ideas?
有任何想法吗? I apologize in advance if this sort of thing has been answered before, but I've tried and searched everything I can think of.
如果之前已经回答过这种事情,我会事先道歉,但我已经尝试并搜索了我能想到的一切。
Try this: 尝试这个:
sortedSample = sorted(sampleToBeSorted, key= lambda x:[(i[1],i[0],i[2]) for i in x])
The key is simply a list of re-ordered tuples according to your criteria 关键是根据您的标准重新排序的元组列表
result: 结果:
[(('A', 31, 'B'), ('D', 32, 'B')),
(('C', 31, 'A'), ('B', 24, 'C'), ('C', 33, 'B')),
(('D', 31, 'A'), ('D', 32, 'B'), ('C', 29, 'B'), ('D', 216, 'C')),
(('D', 31, 'A'), ('D', 52, 'B')),
(('D', 40, 'B'), ('A', 32, 'C')),
(('D', 52, 'B'), ('D', 32, 'B'))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.