[Tutor] Rearranging a list
Steven D'Aprano
steve at pearwood.info
Thu Feb 26 13:51:05 CET 2015
Ah wait, the penny drops! Now I understand what you mean!
On Thu, Feb 26, 2015 at 07:13:57AM -0500, Ken G. wrote:
> 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?
Here's your list again:
[0, 0, 21, 35, 19, 42]
I think using a list is the wrong answer. I think you should use a
dictionary:
d = {0: 0, 1: 0, 2: 21, 3: 35, 4: 19, 5: 42}
for key, value in sorted(d.items(), reverse=True):
print(key, value)
which gives this output:
5 42
4 19
3 35
2 21
1 0
0 0
How should you build the dict in the first place? There's an easy way,
and an even easier way. Here's the easy way.
# count the numbers
numbers = [2, 3, 1, 4, 0, 4, 2, 5, 2, 3, 4, 1, 1, 1, 3, 5]
counts = {}
for n in numbers:
i = counts.get(n, 0)
counts[n] = i + 1
print(counts)
which gives output:
{0: 1, 1: 4, 2: 3, 3: 3, 4: 3, 5: 2}
Here's the even easier way:
from collections import Counter
counts = Counter(numbers)
print(counts)
which gives very similar output:
Counter({1: 4, 2: 3, 3: 3, 4: 3, 5: 2, 0: 1})
In both cases, you then run the earlier code to print the items in
order:
for key, value in sorted(counts.items(), reverse=True):
print(key, value)
--
Steve
More information about the Tutor
mailing list