сортировка списка по возрастанию и убыванию

Python – sorting a list in ascending and descending order

Hi everyone! Sometimes you need to sort the list in ascending and descending order. There is a very simple solution to this issue;)

Actually, I described some options here. But – in the standard Python distribution there is a library heapq , which I will not describe the full functionality of now (I will describe later, yes), and which will help us organize the sorting of the list in ascending and descending order. Let me give you an example that allows you to sort a list in ascending and descending order in just one line. So:

  1. import random #connected a library for working with random numbers
  2. import heapq #connected a library for working with list
  3. list=[random.randrange(1,1000) for i in range(100)] #Generated a list consisting of random numbers, where random.randrange (1,1000) is a random number from 1 to 1000, range (100) is the number of elements in the created list
  4. print(list) #Output the resulting list to the console
  5. print(heapq.nsmallest(len(list), list)) #Displayed the result of sorting the list in ascending order
  6. print(heapq.nlargest(len(list), list)) #Displayed the result of sorting the list in descending order

As you can see, everything is simple. And without magic. Thanks for attention! As always – if you have any questions, write to the mail or Telegram.