简体   繁体   中英

.count() occurrences within range() in list

Simple question that I couldn't find a answer to, maybe I'm just stupid and not searching the right stuff but here is the code.

list = [1,2,2,3,4,4,4,5,6,7,7,8,9,9,9,10,10]
ranges = [range(1, 3), range(3, 6), range(6, 10)]

rangesCount = []

for i in ranges:
     rangesCount.append(list.count(i))


 print(rangesCount)

Basically I want it to count the occurrences of numbers in a certain range. So the printed output should be [3, 5, 9]

list.count is used to count occurrences of a specified value in a list, not to check for inclusion in range objects.

One solution is to use sum with a generator expression:

L = [1,2,2,3,4,4,4,5,6,7,7,8,9,9,9,10,10]
ranges = [range(1, 3), range(3, 6), range(6, 10)]

rangesCount = []
for rng in ranges:
    rangesCount.append(sum(x in rng for x in L))

print(rangesCount)
# [3, 5, 7]

More efficient algorithms are available, eg bisect , as well as vectorised solutions via 3rd party libraries, eg np.digize [NumPy], pd.cut [Pandas].

The .count method cannot count ranges, only values

You can easily build a range counter using a nice thing called map :

l = [1,2,2,3,4,4,4,5,6,7,7,8,9,9,9,10,10]
list(map(l.count, range(2,4)))
>> [2, 1]
sum(map(l.count, range(2,4)))
>> 3

Then nest it in a for loop:

list(sum(map(l.count, x) )for x in (range(1, 3), range(3, 6), range(6, 10)))
>> [3, 5, 7]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM