Во-первых, удостоверьтесь, что Вы задаете себе вопрос, "Я должен действительно использовать Массив здесь"?
, Если Вы не создаете что-то, где скорость имеет наибольшее значение, введенный Список, как List<int>
является, вероятно, способом пойти. Единственное время я когда-либо использую массивы, для массивов байтов при отправке материала по сети. Кроме этого, я никогда не касаюсь их.
Perhaps the function you are seeking is matplotlib.mlab.rec_groupby:
import matplotlib.mlab
data=np.array(
[('Aaron','Digger',1),
('Bill','Planter',2),
('Carl','Waterer',3),
('Darlene','Planter',3),
('Earl','Digger',7)],
dtype=[('name', np.str_,8), ('job', np.str_,8), ('income', np.uint32)])
result=matplotlib.mlab.rec_groupby(data, ('job',), (('income',np.mean,'avg_income'),))
yields
('Digger', 4.0)
('Planter', 2.5)
('Waterer', 3.0)
matplotlib.mlab.rec_groupby
returns a recarray:
print(result.dtype)
# [('job', '|S7'), ('avg_income', '<f8')]
You may also be interested in checking out pandas, which has even more versatile facilities for handling group-by operations.
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#dictionary-get-method
should help to make it a little prettier, more pythonic, more efficient possibly. I'll come back later to check on your progress. Maybe you can edit the function with this in mind? Also see the next couple of sections.
Your if k not in data_per_key.keys()
could be rewritten as if k not in data_per_key
, but you can do even better with defaultdict
. Here's a version that uses defaultdict
to get rid of the existence check:
import collections
def aggregate(data, key, value, func):
data_per_key = collections.defaultdict(list)
for k,v in zip(data[key], data[value]):
data_per_key[k].append(v)
return [(k,func(data_per_key[k])) for k in data_per_key.keys()]