Collections module in Python behaves strange? -



Collections module in Python behaves strange? -

hi python users,

i not 100% sure seems there bug in pythons function collections.counter() part in collections module. function collections.counter() should count occurrences of numbers in list, in other words should determine frequency of numbers in list (vector). should not matter if these numbers floats or integers. in many occasions job not always, , here illustration when fails give right answer:

import numpy np itertools import groupby import collections import matplotlib.pyplot plt data_1=[250, 250, 251, 251, 251, 251, 252, 252, 252, 252, 253, 253, 253, 253, 254, 254, 254, 254, 254] data_2=[250, 250, 251, 251, 251, 251, 252, 252, 252, 252, 253, 253, 253, 253, 254, 254, 254, 254, 254, 255, 256, 256] # determine no. of repetitions sweeped wavelengths d2=collections.counter(data_1) # bug in collections module data_2 not data_1 d3=d2.values() print d3

using collections.counter on data_1 list give right reply (d3) occurrences:

[2, 4, 4, 4, 5]

however, if apply collections.counter on data_2 next reply (d3):

[2, 2, 4, 4, 4, 5, 1]

which wrong. should read [2, 4, 4, 4, 5, 1, 2]. seems collections.counter() interchanges elements, can not find logical explanations why that. btw. using python 2.7.5

what sentiment on this?

ps1: dictionary function dict((i,data_2.count(i)) in data_2) gives same wrong reply data_2 collections.counter(data_2).

ps2: solution seems groupby function itertools module:

from itertools import groupby d3=[len(list(group)) key, grouping in groupby(data_2)]

collections.counter subtype of dict. , dictionaries don’t have order. such, output using d.values() on counter object (the dictionary!) arbitrary , not want.

if want order values key, should sort values key first , homecoming values:

>>> [v k, v in sorted(counter(data_1).items(), key=lambda x: x[0])] [2, 4, 4, 4, 5] >>> [v k, v in sorted(counter(data_2).items(), key=lambda x: x[0])] [2, 4, 4, 4, 5, 1, 2]

python collections numbers counter

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -