如果它小于或等于列表中的值,我如何获得每个值的频率和频率之和?

时间:2017-11-02 21:56:05

标签: python python-3.x

sample = [1,2,2,4,4,3,4,3,4,3]

depot_1=[]
depot_2=[]
tempdepot_1=[]
tempdepot_2 = []

def sample_calc (sample):

    for item_1 in sorted(sample):
        depot_1.append(item_1)
        tempdepot_1.append(sample.count(item_1))


    for item_2 in tempdepot_1:
        depot_2.append(item_2/len(sample))

    tempdepot_3=[ sum( depot_2[:x] ) for x in range( 1, len(depot_2)+1 ) ]


    print(depot_1)
    print(tempdepot_1)
    print(depot_2)
    print(tempdepot_3)

sample_calc (sample) 

我正在尝试获取两个列表,一个是[原始列表],第二个是[排序列表]中每个值的频率,以及相等和较小值的频率之和。

期望的输出:

depot_1     = [1,2,2,3,3,3,4,4,4,4]
tempdepot_3 = [0.1, 0.3, 0.3, 0.6, 0.6, 0.6, 1.0, 1.0, 1.0, 1.0]  

你能帮忙[tempdepot_3]清单吗? (没有图书馆)

2 个答案:

答案 0 :(得分:0)

所以,只需要一个计数器(我正在使用collections,这很简单就可以使用普通的dict了。然后我得到累积比例的映射,他们使用映射来构建最终列表:

>>> import collections
>>> sample = [1,2,2,4,4,3,4,3,4,3]
>>> N = len(sample)
>>> depot = sorted(sample)
>>> counts = collections.Counter(depot)
>>> counts
Counter({4: 4, 3: 3, 2: 2, 1: 1})
>>> p = 0
>>> props = {}
>>> for k, v in sorted(counts.items()): # Necessary to sort, dicts are unordered
...     p += v
...     props[k] = p / N
...
>>> props
{1: 0.1, 2: 0.3, 3: 0.6, 4: 1.0}

最后:

>>> tempdepot = [props[x] for x in depot]
>>> tempdepot
[0.1, 0.3, 0.3, 0.6, 0.6, 0.6, 1.0, 1.0, 1.0, 1.0]

答案 1 :(得分:0)

没有collections库的另一种不那么优雅的方法是:

sample = [1,2,2,4,4,3,4,3,4,3]
depot_1 = sorted(sample)
print(depot_1)

tempdepot_3 = []

freq = depot_1.count(depot_1[0])/len(depot_1)
tempdepot_3.append(freq)

for i in range(1,len(depot_1)):

  freq = depot_1.count(depot_1[i])/len(depot_1)

  if depot_1[i]==depot_1[i-1]:
    tempdepot_3.append(tempdepot_3[i-1])
  else:
    tempdepot_3.append(round(freq + tempdepot_3[i-1],1))

print(tempdepot_3)

输出结果为:

[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
[0.1, 0.3, 0.3, 0.6, 0.6, 0.6, 1.0, 1.0, 1.0, 1.0]

但是,最好使用Python的标准库来提高代码的性能。