ss = [(0,'bb','jj'), (1,'aa','mm'), (2,'aa','kk'),(3,'bb','ee'),(4,'gg','ff')]
for x in ss:
pp = <somthing>
Using Python, is it possible to insert from ss into pp and maintain pp sorted by two attributes, let's say by the 2nd then 3rd position in order to have the following result (both attributes ascending):
pp = [(2, 'aa', 'kk'), (1, 'aa', 'mm'), (3, 'bb', 'ee'), (0, 'bb', 'jj'), (4, 'gg', 'ff')]
Or (both attributes descending):
pp = [(4, 'gg', 'ff'), (0, 'bb', 'jj'), (3, 'bb', 'ee'), (1, 'aa', 'mm'), (2, 'aa', 'kk')]
I don't want to use the following two statments after the loop which already do the job:
pp = sorted(ss, key = operator.itemgetter(1, 2))
pp = sorted(ss, key = operator.itemgetter(1, 2), reverse=True)
Because i am dealing with a very long list and i already have the loop which i want to reuse for sorting as well.
pp
in your loop (or just writepp.extend(ss)
), then callpp.sort
with the same arguments as the calls tosorted
that you don't want to do. Thank to Timsort, this is the efficient way to maintain a sorted list in Python.pp
. Then ignore the part aboutextend
. I don't understand why you wouldn't want to use thesorted
lines. Regardless of the size of the list,sorted
is an efficient way to create a sorted copy of it. You will not get better performance by repeatedly inserting each element into its correct place. That's called "insertion sort", and if it was a good sorting algorithm thensorted
would probably use it. For large lists it isn't good.heapq
module functions. But it would require extra work because your sort criterion ain't trivial. Take a look at this: docs.python.org/2/library/…