[Tutor] Rearranging a list
Peter Otten
__peter__ at web.de
Thu Feb 26 13:30:54 CET 2015
Ken G. wrote:
> Assuming I have the following list and code how do I best be able
> rearrange the list as stated below:
>
> list = [0, 0, 21, 35, 19, 42]
>
> Using print list[2:6] resulted in the following:
>
> 2 21
> 3 35
> 4 19
> 5 42
>
> I would like to rearrange the list as follow:
>
> 5 42
> 3 35
> 2 21
> 4 19
>
> I tried using list.reverse() and print list[0,6] and it resulted in:
>
> [42, 19, 35, 21, 0, 0] or as printed:
>
> 0 42
> 1 19
> 2 35
> 3 21
> 4 0
> 5 0
>
> In another words, I would desire to show that:
>
> 5 appears 42 times
> 3 appears 35 times
> 2 appears 21 times
> 4 appears 19 times
>
> but then I lose my original index of the numbers by reversing. How do I
> best keep the original index number to the rearrange numbers within a
> list?
Don't rearrange the original list, make a new one instead:
>>> frequencies = [0, 0, 21, 35, 19, 42]
>>> wanted_indices = [5, 3, 2, 4]
>>> [frequencies[i] for i in wanted_indices]
[42, 35, 21, 19]
Or look up the values as you print them:
>>> for i in wanted_indices:
... print(i, "appears", frequencies[i], "times")
...
5 appears 42 times
3 appears 35 times
2 appears 21 times
4 appears 19 times
The expression [frequencies[i] for i in wanted_indices] is called "list
comprehension" and is a shortcut for a loop:
>>> result = []
>>> for i in wanted_indices:
... result.append(frequencies[i])
...
>>> result
[42, 35, 21, 19]
More information about the Tutor
mailing list