[Tutor] Rearranging a list of numbers with corresponding index

Peter Otten __peter__ at web.de
Fri Mar 13 15:21:23 CET 2015


Ken G. wrote:

> I have been keeping track of numbers drawn in our local lotto drawings
> into a list format as shown in a short example below. Using such list, I
> am able to determine how often a number appears within the last 100 plus
> drawings.
> 
> The length of my lists range from 5, 15, 35, 59and 75 long. I will give
> an example of one of my short list.
> 
> PowerPlay = [0, 0, 61, 32, 11, 14]
> 
> Disregarding index 0 and 1, I can see and print the following:
> 
> Index    Number
> 2 61
> 3 32
> 4     11
> 5     14
> 
> showing that number 2 appears 61 times, number 3 appears 32 times,
> number 4 appears 11 times and number 5 appears 14 times within last 100
> plus drawings.
> 
> How I best rearrange the numbers from high to low with its corresponding
> index number such as below:
> 
> Number Index
> 61                2
> 32                3
> 14 5
> 11     4
> 
> showing the number 2 appears 61 times, number 3 appears 32 times, number
> 5 appears 14 times and number 4 appears 11 times. I know that using
> 
> MegaBall.reverse()
> 
> sort the number from high to low but the index numbers still remain in
> the same positions.
> 
> Thanks for pointing out the way to do this.

The initial list:

>>> power_play = [0, 0, 61, 32, 11, 14]

Use enumerate() to get index, frequency pairs:

>>> list(enumerate(power_play))
[(0, 0), (1, 0), (2, 61), (3, 32), (4, 11), (5, 14)]

Sort the pairs:

>>> sorted(enumerate(power_play))
[(0, 0), (1, 0), (2, 61), (3, 32), (4, 11), (5, 14)]

Provide a key to sort after the second value, i. e. the frequency in the 
(index, frequency) pairs:

>>> def second_value(item):
...     return item[1]
... 
>>> sorted(enumerate(power_play), key=second_value)
[(0, 0), (1, 0), (4, 11), (5, 14), (3, 32), (2, 61)]

Note that instead of writing your own custom function or lambda you could 
also use operator.itemgetter(1) from the operator module in the stdlib.

Sort in reverse order:

>>> sorted(enumerate(power_play), key=second_value, reverse=True)
[(2, 61), (3, 32), (5, 14), (4, 11), (0, 0), (1, 0)]


Print the output for frequencies > 0:

>>> pairs = sorted(enumerate(power_play), key=second_value, reverse=True)
>>> for index, freq in pairs:
...     if freq == 0:
...         break
...     print(freq, index, sep="\t")
... 
61      2
32      3
14      5
11      4




More information about the Tutor mailing list