2017-09-24 42 views
0

我已經建立由下面的指令的一隨機列表:如何統計隨機生成列表中的值的數量?

import random 
a=[random.randrange(0,100) for i in xrange(50)] 
print a 

現在,可能是什麼命令用於計數是0和9,圖10和19,20和29之間的值的數目,等等。

我可以如下打印出來:

import random 
a = [random.randrange(0,100) for i in xrange(50)] 
for b in a: 
    if b<10: 
    print b 

但是,我不知道怎麼寫命令打印B之後計數的值的數量。 感謝您的意見。

回答

1

只是要一本字典,枚舉和計數。

>>> import random 
>>> a = [random.randrange(0,100) for i in xrange(50)] 
>>> a 
[88, 48, 7, 92, 22, 13, 66, 38, 72, 34, 8, 18, 13, 29, 48, 63, 23, 30, 91, 40, 96, 89, 27, 8, 92, 26, 98, 83, 31, 45, 81, 4, 55, 4, 42, 94, 64, 35, 19, 64, 18, 96, 26, 12, 1, 54, 89, 67, 82, 62] 
>>> counts = {} 
>>> for i in a:  
     t = counts.setdefault(i/10,0) 
     counts[i/10] = t + 1 


>>> counts 
{0: 6, 1: 6, 2: 6, 3: 5, 4: 5, 5: 2, 6: 6, 7: 1, 8: 6, 9: 7} 
# Means: 0-9=> 6 numbers, 10-19=> 6 numbers etc. 
0

您可以使用bisect.bisect(...)實現這一爲:

from bisect import bisect 
import random 

randon_nums = [random.randint(0,100) for _ in xrange(100)] 

bucket = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # can also be created using: 
                #  range(10, 101, 10) 

randon_nums.sort() # sort the initial list in order to use it with `bisect` 

counts = [] 
last_bucket_count = 0 # to track the count of numbers in last calculated bucket 

for range_max in bucket: 
    i = bisect(randon_nums, range_max, end_index) 
    counts.append(i - last_bucket_count) 
    last_bucket_count = i 

樣品試驗:

random_nums值是:

>>> randon_nums 
[0, 1, 4, 5, 5, 5, 5, 6, 7, 7, 8, 8, 10, 10, 11, 11, 12, 13, 13, 13, 16, 17, 18, 18, 18, 18, 19, 20, 21, 22, 24, 24, 25, 25, 26, 26, 26, 26, 26, 29, 30, 30, 31, 33, 37, 37, 38, 42, 42, 43, 44, 44, 47, 47, 49, 51, 52, 55, 55, 57, 57, 58, 59, 63, 63, 63, 63, 64, 64, 65, 66, 67, 68, 71, 73, 73, 73, 74, 77, 79, 82, 83, 83, 83, 84, 85, 87, 87, 88, 89, 89, 90, 92, 93, 95, 96, 98, 98, 99, 99] 

上述程序返回count爲:

>>> counts 
[ 14, 14, 14,  5,  8,  8,  10, 7, 12, 8] 
# ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
# 0-10 10-20 20-30 30-40 40-50 50-60 60-70 70-80 80-90 90-100 
1

,如果我理解正確的話,那麼這樣:

import random 
a = [random.randrange(0,100) for i in xrange(50)] 
print len(filter(lambda x: 0 <= x < 10,a)) 
print len(filter(lambda x: 10 <= x < 20,a)) 

0

在數據分析和統計中,這被稱爲「分箱」。如果你在'網箱'和'箱子'這樣的網絡上徘徊,你會發現大量有關軟件的頁面以及如何做到這一點。

但是,一個非常好的使用Python,numpy的卓越產品。

>>> import random 
>>> a=[random.randrange(0,100) for i in range(50)] 
>>> from numpy import histogram 

在你的情況,你需要建立哪些是-0.5,9.5,19.5,29.5,39.5,49.5,59.5,69.5,79.5,89.5,和99.5倉的終點。 (我選擇-0.5作爲低端,只是因爲它讓我的計算更容易。)histogram計算在這些數字給出的每個範圍內有多少物品,成對(-0.5至9.5,9.5至19.5等) )。

>>> bins = [-0.5+10*i for i in range(11)] 
>>> hist,_ = histogram(a, bins) 

這就是結果。

>>> hist 
array([6, 6, 2, 6, 2, 3, 6, 9, 5, 5], dtype=int64) 
+0

感謝您提供的信息。 – Nourolah

+0

非常歡迎。 –