[Tutor] Rearranging a list of numbers with corresponding index

Dave Angel davea at davea.name
Fri Mar 13 15:38:56 CET 2015


On 03/13/2015 09:57 AM, 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.
>

Make a list of tuples by doing something like:
new_list = [ (cnt, index) for index, cnt in enumerate(power_play) ]

to produce:
   [ (0, 0), (0, 1), (61, 2), (32, 3), (11, 4), (14, 5) ]

then sort it with reverse=True.  When you print it, just omit the items 
that have zero as their count.  (they'll be at the end, anyway)

Lots of other variants, some more concise.  And other approaches might 
be cleaner if we change how we generate the list.

(I tried it briefly using Python 3.4)


-- 
DaveA


More information about the Tutor mailing list