我有一个元组列表的列表。每个元组的格式为(string,int)
,例如
lst = list()
lst.append([('a',5),('c',10),('d',3),('b',1)])
lst.append([('c',14),('f',4),('b',1)])
lst.append([('d',22),('f',2)])
将
int
视为不同文本块中每个字符串的计数。我需要做的是生成出现在顶部的
N
字符串及其累积计数的列表。因此,在上面的示例中,a
出现5次,b
出现两次,c
出现24次,等等。如果N=2
,那么我将不得不生成一对平行列表['d','c']
和或元组[25,24]
列表。我需要尽快做。我的机器有很多RAM,因此内存不是问题。我有这个实现:
import numpy as np
def getTopN(lst,N):
sOut = []
cOut = []
for l in lst:
for tpl in l:
s = tpl[0]
c = tpl[1]
try:
i = sOut.index(s)
cOut[i] += c
except:
sOut.append(s)
cOut.append(c)
sIndAsc = np.argsort(cOut).tolist()
sIndDes = sIndAsc[::-1]
cOutDes = [cOut[sir] for sir in sIndDes]
sOutDes = [sOut[sir] for sir in sIndDes]
return sOutDes[0:N],cOutDes[0:N]
有一种更好的方法,但是那会是什么呢?
最佳答案
import collections
c = collections.Counter()
for x in lst:
c.update(dict(x))
print(c.most_common(2))
输出:
[('d', 25), ('c', 24)]
Counter
基本上是具有一些附加功能的字典,因此查找值并将其添加到当前计数中确实非常快。 dict(x)
只会将元组列表转换为常规字典,将字符串映射到数字,然后update
的Counter
方法将添加这些计数(而不是像常规字典那样覆盖值)。或者,使用
defaultdict
的更手动的方法:c = collections.defaultdict(int)
for x, y in (t for x in lst for t in x):
c[x] += y
return [(k, c[k]) for k in sorted(c, key=c.get, reverse=True)][:2]
正如John在评论中指出的,
defaultdict
的确确实更快:In [2]: %timeit with_counter()
10000 loops, best of 3: 17.3 µs per loop
In [3]: %timeit with_dict()
100000 loops, best of 3: 4.97 µs per loop
关于python - 合并和排序元组列表的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33917653/