【发布时间】:2017-02-12 11:04:35
【问题描述】:
给定一个集合列表(字符串集合,例如setlist = [{'this','is'},{'is','a'},{'test'}]),想法是加入共享字符串的成对联合集合。下面的 sn-p 采用了测试成对重叠、连接和使用内部循环中断重新开始的字面方法。
我知道这是行人的方法,对于可用大小的列表(200K 组,2 到 10 个字符串)确实需要很长时间。
关于如何提高效率的任何建议?谢谢。
j = 0
while True:
if j == len(setlist): # both for loops are done
break # while
for i in range(0,len(setlist)-1):
for j in range(i+1,len(setlist)):
a = setlist[i];
b = setlist[j];
if not set(a).isdisjoint(b): # ... then join them
newset = set.union( a , b ) # ... new set
del setlist[j] # ... drop highest index
del setlist[i] # ... drop lowest index
setlist.insert(0,newset) # ... introduce consolidated set, which messes up i,j
break # ... back to the top for fresh i,j
else:
continue
break
【问题讨论】:
-
什么是
setlist? -
我已经编辑了问题并添加了一个设置列表示例,预期输出为
[{'this','is','a'},{'test'}]。 -
所以你的预期输出是“这是一个测试”?
标签: python python-2.7