从这里How do I remove element from a list of tuple if the 2nd item in each tuple is a duplicate?,我能够从1个元组列表中删除元组中第2个元素的副本。
假设我有两个元组列表:
alist = [(0.7897897,'this is a foo bar sentence'),
(0.653234, 'this is a foo bar sentence'),
(0.353234, 'this is a foo bar sentence'),
(0.325345, 'this is not really a foo bar'),
(0.323234, 'this is a foo bar sentence'),]
blist = [(0.64637,'this is a foo bar sentence'),
(0.534234, 'i am going to foo bar this sentence'),
(0.453234, 'this is a foo bar sentence'),
(0.323445, 'this is not really a foo bar')]
如果第二个元素相同(score_from_alist * score_from_blist)并且达到所需的输出,我需要结合得分:
clist = [(0.51,'this is a foo bar sentence'), # 0.51 = 0.789 * 0.646
(0.201, 'this is not really a foo bar')] # 0.201 = 0.325 * 0.323
目前,我正在通过这样做来实现克隆,但是当我的alist和blist有大约5500多个元组时它需要5秒以上,其中第二个元素每个大约有20-40个单词。有没有办法让以下功能更快?
def overlapMatches(alist, blist):
start_time = time.time()
clist = []
overlap = set()
for d in alist:
for dn in blist:
if d[1] == dn[1]:
score = d[0]*dn[0]
overlap.add((score,d[1]))
for s in sorted(overlap, reverse=True)[:20]:
clist.append((s[0],s[1]))
print "overlapping matches takes", time.time() - start_time
return clist
答案 0 :(得分:3)
我会使用字典/集来消除重复并提供快速查找:
alist = [(0.7897897,'this is a foo bar sentence'),
(0.653234, 'this is a foo bar sentence'),
(0.353234, 'this is a foo bar sentence'),
(0.325345, 'this is not really a foo bar'),
(0.323234, 'this is a foo bar sentence'),]
blist = [(0.64637,'this is a foo bar sentence'),
(0.534234, 'i am going to foo bar this sentence'),
(0.453234, 'this is a foo bar sentence'),
(0.323445, 'this is not really a foo bar')]
bdict = {k:v for v,k in reversed(blist)}
clist = []
cset = set()
for v,k in alist:
if k not in cset:
b = bdict.get(k, None)
if b is not None:
clist.append((v * b, k))
cset.add(k)
print(clist)
在这里,blist
用于消除除每个句子的第一个外观之外的所有内容,并提供按句子快速查找。
如果您不关心clist
的排序,可以稍微简化一下结构:
bdict = {k:v for v,k in reversed(blist)}
cdict = {}
for v,k in alist:
if k not in cdict:
b = bdict.get(k, None)
if b is not None:
cdict[k] = v * b
print(list((k,v) for v,k in cdict.items()))
答案 1 :(得分:1)
如果元组中的第一个项目按降序排序,则将单元格中存在重复项的最高第1个项目保留为元组,并且如果相应的第二个项目中的相应第二个项目,则合并两个列表中的分数元组是一样的:
# remove duplicates (take the 1st item among duplicates)
a, b = [{sentence: score for score, sentence in reversed(lst)}
for lst in [alist, blist]]
# merge (leave only tuples that have common 2nd items (sentences))
clist = [(a[s]*b[s], s) for s in a.viewkeys() & b.viewkeys()]
clist.sort(reverse=True) # sort by (score, sentence) in descending order
print(clist)
输出:
[(0.510496368389, 'this is a foo bar sentence'),
(0.10523121352499999, 'this is not really a foo bar')]