Given a list like this one
arr = [1, 1, 2, 2, 2, 3, 3]
I would like to compute the number of occurencies of each element and storing it in a new list but using a list comprehension like this:
occ = [arr.count(e) for e in arr]
but this prints out the original array: [1, 1, 2, 2, 2, 3, 3]
instead of [2, 3, 2]
which are respectively the number of occurences of 1, 2, and 3 in the input arry.
Why is that happening and how to fix it?
NB: it is mandatory to use a list comprehension if possible.
Well, the reason is tht when you do
arr = [1, 1, 2, 2, 2, 3, 3]
and arr.count(1), you'll get the number of occurencies of the number 1 in the list arr. And then when you do
occ = [arr.count(e) for e in arr]
you are actually computing arr.count(1) 2 times, then arr.count(3) three times, and then arr.count(3) two times.
So, what you have to do in order to not repeat the numbers is count the unique numbers in the list, which are just 1, 2, and 3. So the right code would be:
occ = [arr.count(e) for e in set(arr)]
and now when you print the list, you'll get [2,3,2] as expected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.