grouping and sorting within groups using another list

David Raymond David.Raymond at tomtom.com
Wed Sep 2 14:21:42 EDT 2020


Would it be something as simple as:

rows.sort(key = lambda x: (x[0], x[3], x[4], sort_list.index(x[6])))



-----Original Message-----
From: Python-list <python-list-bounces+david.raymond=tomtom.com at python.org> On Behalf Of Larry Martell
Sent: Wednesday, September 2, 2020 1:55 PM
To: Python <python-list at python.org>
Subject: grouping and sorting within groups using another list

I have a list of tuples, and I want to group them by 3 items (0, 3, 4)
and then within each group sort the data by a 4th item (6) using a
sort order from another list. The list is always ordered by the 3
grouping items.

For example, if I have this list:
rows =
[('a', 'b', 'c', 'd', 'e', 'f', 'blue', ....),
 ('a', 'x', 'y', 'd', 'e', 'f', 'green', ....),
 ('a', 'q', 'w', 'd', 'e', 'f', 'white', ....),
 ('p', 'x', 'y', 'd', 'e', 'f', 'white', ....),
 ('p', 'x', 'y', 'd', 'e', 'f', ' 'blue', ...),
 ('p', 'x', 'y', 'd', 'e', 'f', ' 'green', ...),
 ('z', 'x', 'y', 'm', 'n', 'o', 'green, ...),
 ('z', 'x', 'y', 'm', 'n', 'o', 'white, ...),
 ('z', 'x', 'y', 'm', 'n', 'o', 'blue, ...),
]

and I have a list:

sort_list = ['blue', 'white', 'green']

Then the result list would be:

[('a', 'b', 'c', 'd', 'e', 'f', 'blue', ....),
 ('a', 'x', 'y', 'd', 'e', 'f', 'white', ....),
 ('a', 'q', 'w', 'd', 'e', 'f', 'green', ....),
 ('p', 'x', 'y', 'd', 'e', 'f', 'blue', ....),
 ('p', 'x', 'y', 'd', 'e', 'f', ' 'white', ...),
 ('p', 'x', 'y', 'd', 'e', 'f', ' 'green', ...),
 ('z', 'x', 'y', 'm', 'n', 'o', 'blue, ...),
 ('z', 'x', 'y', 'm', 'n', 'o', 'white, ...),
 ('z', 'x', 'y', 'm', 'n', 'o', 'green, ...),
]

Been trying to do with using groupby but have not been successful.
-- 
https://mail.python.org/mailman/listinfo/python-list


More information about the Python-list mailing list