O
O
Olga Chernaya2016-02-03 19:39:45
Python
Olga Chernaya, 2016-02-03 19:39:45

How to sort a list nicely in Python?

Task:
There is a list of pairs of elements:
compound_transpositions =
There are coefficients of a linear function:
coefficients = [17, 69, 84, 3 , 46, 97, 12, 68, 70, 10]
We need to sort the compound_transpositions by increasing the difference of the corresponding coefficients of the linear function.
We managed to get the differences themselves, for example:
keys = map(lambda x: T.coefficients[x[0]]-T.coefficients[x[1]], p.compound_transpositions())
>>>[81, -43, -51, 85]
That is, the first pair [2, 3] corresponds to the difference between the second and third coefficients of the function: 84-3=81. Etc.
Question: how to combine it now. The main thing: the task is simple and clear how to do it algorithmically. But not just a solution, but a beautiful solution is of interest. Python style, one line.
True Madskills hackers, tell me please. Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Klimenko, 2016-02-03
@OlBlack

>>> compound_transpositions = 
>>> coefficients = [17, 69, 84, 3, 46, 97, 12, 68, 70, 10]
>>> compound_transpositions.sort(key=lambda x: coefficients[x[0]]-coefficients[x[1]])
>>> compound_transpositions

J
JRazor, 2016-02-03
@JRazor

What makes you think Python style is one line? Pythonists, on the contrary, do not like such lines.

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complicated is better than confusing.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability matters.
  • Special occasions are not special enough to break the rules.
  • At the same time, practicality is more important than impeccability.
  • Mistakes should never be hushed up.
  • If they are not explicitly hushed up.
  • When faced with ambiguity, resist the temptation to guess.
  • There should be one—and preferably only one—obvious way to do this.
  • Although it may not be obvious at first if you are not Dutch[9].
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is difficult to explain, the idea is bad.
  • If the implementation is easy to explain, the idea is probably good.
  • Namespaces are great! Let's make more of them!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question