gingerbeardman - 9 months ago 47

Python Question

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:

`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.

Answer Source

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'))]
```