在numpy/中scipy,是否有一种有效的方法来获取数组中唯一值的频率计数?
这些方面的东西:
x = array( [1,1,1,2,2,2,5,25,1,1] )
y = freq_count( x )
print y
>> [[1, 5], [2,3], [5,1], [25,1]]
Run Code Online (Sandbox Code Playgroud)
(对你来说,R用户在那里,我基本上都在寻找这个table()功能)
我希望array.array比列表更快,因为数组似乎是未装箱的.
但是,我得到以下结果:
In [1]: import array
In [2]: L = list(range(100000000))
In [3]: A = array.array('l', range(100000000))
In [4]: %timeit sum(L)
1 loop, best of 3: 667 ms per loop
In [5]: %timeit sum(A)
1 loop, best of 3: 1.41 s per loop
In [6]: %timeit sum(L)
1 loop, best of 3: 627 ms per loop
In [7]: %timeit sum(A)
1 loop, best of 3: 1.39 s per loop
Run Code Online (Sandbox Code Playgroud)
可能是造成这种差异的原因是什么?
我正在尝试编写一个count(s, chars)带字符串s和字符列表的函数chars.该函数应计算给出的字母出现次数chars.它应该返回一个字典,其中键是字符列表中给出的字符chars.
例如:
In [1]: s = "Another test string with x and y but no capital h."
In [2]: count(s, ['A', 'a', 'z'])
Out[2]: 'A': 1, 'a': 3, 'z': 0
Run Code Online (Sandbox Code Playgroud)
我制作了一些代码,可以计算字符串的所有字符并返回它的字典:
return {i: s.count(i) for i in set(s)}
Run Code Online (Sandbox Code Playgroud)
但我不确定你将如何使用特定字符列表并返回字典...
我需要一个解决方案,从非唯一列表中提取唯一元素,并计算其重复元素.
该解决方案的目的是在算法中使用它来从非唯一列表创建唯一组合.在这种情况下创建组合的列表大小通常非常小(少于50个元素),但我的目标是找到尝试随时随地优化的最快代码(即使只获得非常少量的运行时间) ).
Pythons collections模块提供了一个适合专业的目的collections.Counter,但有些情况下,使用简单的字典而不是collections.Counter导致更快的代码,就像你可以使用下面的代码检查自己:
from time import time as t
from timeit import timeit as tt
from collections import Counter
def counter(iterable):
dctCounter = {}
for item in iterable:
if item in dctCounter:
dctCounter[item] += 1
else:
dctCounter[item] = 1
return dctCounter
for n, N in [(1,10), (10,1), (1,50), (50,1), (1,100), (100,1), (1,200), (200, 1), (1, 500), (500, 1), (1, 1000), (1000,1)]:
lstItems = n*list(range(N))
for noLoops in [10**p for p in range(5, 6)]: …Run Code Online (Sandbox Code Playgroud)