我在过滤字符串列表时遇到了一些麻烦。我发现了类似的问题here但不是我需要的。
输入列表是:
l = ['ab', 'xc', 'abb', 'abed', 'sdfdg', 'abfdsdg', 'xccc']
,预期结果是
['ab', 'xc', 'sdfdg']
结果中项目的顺序并不重要
过滤功能必须快,因为列表的大小很大
我目前的解决方案是
l = ['ab', 'xc', 'abb', 'abed', 'sdfdg', 'abfdsdg', 'xccc']
for i in range(0, len(l) - 1):
for j in range(i + 1, len(l)):
if l[j].startswith(l[i]):
l[j] = l[i]
else:
if l[i].startswith(l[j]):
l[i] = l[j]
print list(set(l))
修改
使用大输入数据进行多次测试后,列出1500000个字符串,我的最佳解决方案是:
def filter(l):
if l==[]:
return []
l2=[]
l2.append(l[0])
llen = len(l)
k=0
itter = 0
while k<llen:
addkelem = ''
j=0
l2len = len(l2)
while j<l2len:
if (l2[j].startswith(l[k]) and l[k]!= l2[j]):
l2[j]=l[k]
l.remove(l[k])
llen-=1
j-=1
addkelem = ''
continue
if (l[k].startswith(l2[j])):
addkelem = ''
break
elif(l[k] not in l2):
addkelem = l[k]
j+=1
if addkelem != '':
l2.append(addkelem)
addkelem = ''
k+=1
return l2
执行时间约为213秒
Sample imput data - 每一行都是列表中的字符串
答案 0 :(得分:12)
此算法在我的计算机上以0.97秒完成任务,the input file submitted by the author (154MB):
l.sort()
last_str = l[0]
filtered = [last_str]
app = filtered.append
for str in l:
if not str.startswith(last_str):
last_str = str
app(str)
# Commented because of the massive amount of data to print.
# print filtered
算法很简单:首先按字典顺序对列表进行排序,然后搜索第一个字符串,该字符串不以列表的第一个字符为前缀,然后搜索下一个没有前一个未加前缀的字符串,等
如果列表已经排序(您的示例文件似乎已经排序),则可以删除l.sort()
行,这将导致时间和内存的O(n)复杂性。
答案 1 :(得分:8)
您可以按照第一个字母对项目进行分组,只搜索子列表,除非字符串至少包含相同的第一个字母,否则字符串不能以子字符串开头:
from collections import defaultdict
def find(l):
d = defaultdict(list)
# group by first letter
for ele in l:
d[ele[0]].append(ele)
for val in d.values():
for v in val:
# check each substring in the sublist
if not any(v.startswith(s) and v != s for s in val):
yield v
print(list(find(l)))
['sdfdg', 'xc', 'ab']
这正确地过滤了这些单词,正如您在下面的代码中看到的那样,reduce函数没有,'tool'
不应该在输出中:
In [56]: l = ["tool",'ab',"too", 'xc', 'abb',"toot", 'abed',"abel", 'sdfdg', 'abfdsdg', 'xccc',"xcew","xrew"]
In [57]: reduce(r,l)
Out[57]: ['tool', 'ab', 'too', 'xc', 'sdfdg', 'xrew']
In [58]: list(find(l))
Out[58]: ['sdfdg', 'too', 'xc', 'xrew', 'ab']
它也有效地发挥作用:
In [59]: l = ["".join(sample(ascii_lowercase, randint(2,25))) for _ in range(5000)]
In [60]: timeit reduce(r,l)
1 loops, best of 3: 2.12 s per loop
In [61]: timeit list(find(l))
1 loops, best of 3: 203 ms per loop
In [66]: %%timeit
..... result = []
....: for element in lst:
....: is_prefixed = False
....: for possible_prefix in lst:
....: if element is not possible_prefix and element.startswith(possible_prefix):
....: is_prefixed = True
....: break
....: if not is_prefixed:
....: result.append(element)
....:
1 loops, best of 3: 4.39 s per loop
In [92]: timeit list(my_filter(l))
1 loops, best of 3: 2.94 s per loop
如果你知道最小字符串长度总是&gt; 1你可以进一步优化,如果最小长度字符串是2
那么一个单词必须至少有前两个字母的共同点:
def find(l):
d = defaultdict(list)
# find shortest length string to use as key length
mn = len(min(l, key=len))
for ele in l:
d[ele[:mn]].append(ele)
for val in d.values():
for v in val:
if not any(v.startswith(s) and v != s for s in val):
yield v
In [84]: timeit list(find(l))
100 loops, best of 3: 14.6 ms per loop
最后,如果你有骗局,你可能想要从列表中过滤掉重复的单词,但你需要将它们保持比较:
from collections import defaultdict,Counter
def find(l):
d = defaultdict(list)
mn = len(min(l, key=len))
cn = Counter(l)
for ele in l:
d[ele[:mn]].append(ele)
for val in d.values():
for v in val:
if not any(v.startswith(s) and v != s for s in val):
# make sure v is not a dupe
if cn[v] == 1:
yield v
因此,如果速度很重要,使用上述代码的某些变体的实现将比您的天真方法快得多。内存中还存储了更多数据,因此您也应该考虑到这一点。
为了节省内存,我们可以为每个val / sublist创建一个计数器,所以我们一次只存储一个单词的计数器字典:
def find(l):
d = defaultdict(list)
mn = len(min(l, key=len))
for ele in l:
d[ele[:mn]].append(ele)
for val in d.values():
# we only need check each grouping of words for dupes
cn = Counter(val)
for v in val:
if not any(v.startswith(s) and v != s for s in val):
if cn[v] == 1:
yield v
创建一个dict每个循环增加5ms所以仍然&lt; 5k字20ms。
如果数据已排序,则reduce方法应该有效:
reduce(r,sorted(l)) # -> ['ab', 'sdfdg', 'too', 'xc', 'xrew']
在行为之间明确区别:
In [202]: l = ["tool",'ab',"too", 'xc', 'abb',"toot", 'abed',
"abel", 'sdfdg', 'abfdsdg', 'xccc',"xcew","xrew","ab"]
In [203]: list(filter_list(l))
Out[203]: ['ab', 'too', 'xc', 'sdfdg', 'xrew', 'ab']
In [204]: list(find(l))
Out[204]: ['sdfdg', 'too', 'xc', 'xrew', 'ab', 'ab']
In [205]: reduce(r,sorted(l))
Out[205]: ['ab', 'sdfdg', 'too', 'xc', 'xrew']
In [206]: list(find_dupe(l))
Out[206]: ['too', 'xrew', 'xc', 'sdfdg']
In [207]: list(my_filter(l))
Out[207]: ['sdfdg', 'xrew', 'too', 'xc']
In [208]: "ab".startswith("ab")
Out[208]: True
所以ab
重复两次,因此使用集合或字典而不跟踪ab
次出现的时间将意味着我们认为没有其他元素满足条件{{1} } ab
,我们看到的是不正确的。
您还可以使用itertools.groupby根据最小索引大小进行分组:
"ab".startswith(other ) == True
根据您的评论,我们可以调整我的第一个代码,如果您不认为def find_dupe(l):
l.sort()
mn = len(min(l, key=len))
for k, val in groupby(l, key=lambda x: x[:mn]):
val = list(val)
for v in val:
cn = Counter(val)
if not any(v.startswith(s) and v != s for s in val) and cn[v] == 1:
yield v
应该是重复的元素:
"dd".startswith("dd")
在随机的文本样本上运行的运行只需要您自己的代码执行的时间的一小部分:
l = ['abbb', 'xc', 'abb', 'abed', 'sdfdg', 'xc','abfdsdg', 'xccc', 'd','dd','sdfdg', 'xc','abfdsdg', 'xccc', 'd','dd']
def find_with_dupe(l):
d = defaultdict(list)
# group by first letter
srt = sorted(set(l))
ind = len(srt[0])
for ele in srt:
d[ele[:ind]].append(ele)
for val in d.values():
for v in val:
# check each substring in the sublist
if not any(v.startswith(s) and v != s for s in val):
yield v
print(list(find_with_dupe(l)))
['abfdsdg', 'abed', 'abb', 'd', 'sdfdg', 'xc']
两者都返回相同的输出:
In [15]: l = open("/home/padraic/Downloads/sample.txt").read().split()
In [16]: timeit list(find(l))
100 loops, best of 3: 19 ms per loop
In [17]: %%timeit
....: l = open("/home/padraic/Downloads/sample.txt").read().split()
....: for i in range(0, len(l) - 1):
....: for j in range(i + 1, len(l)):
....: if l[j].startswith(l[i]):
....: l[j] = l[i]
....: else:
....: if l[i].startswith(l[j]):
....: l[i] = l[j]
....:
1 loops, best of 3: 4.92 s per loop
答案 2 :(得分:4)
<强> EDIT3 强>
经过一番冥想,我写了这个算法。它比基于Multiple addresses available.
Please select which address to use by entering its number from the list below:
1) 192.168.0.107 (eth1)
2) localhost
的方法快1k倍,该方法基于Padraic Cunningham提供的大随机数据集(感谢该集合)。该算法具有~O(nlogn)复杂度,但仍有一些空间可用于次要优化。它也非常有效。它需要大约n个额外的空间。
reduce
Edit2 这个问题与我的测试中基于def my_filter(l):
q = sorted(l, reverse=True)
first = q.pop()
addfirst = True
while q:
candidate = q.pop()
if candidate == first:
addfirst = False
continue
if not candidate.startswith(first):
if addfirst:
yield first
first, addfirst = candidate, True
if addfirst:
yield first
的算法一样快,但这种比较取决于所使用的数据集。我只是将一个教科书页面解析成文字。该算法基于以下观察。设A,B和C为字符串,len(A)&lt; min(len(B),len(C))。注意,如果A是B的前缀,那么它足以检查A是否是C的前缀以表示存在前缀C.
reduce
原帖 这是我提出的原始算法。实际上它是你算法的简洁版本。
def my_filter(l):
q = sorted(l, key=len)
prefixed = []
while q:
candidate = q.pop()
if any(candidate.startswith(prefix) for prefix in prefixed):
continue
if any(candidate.startswith(string) for string in q):
prefixed.append(candidate)
else:
yield candidate
演示&GT;&GT;&GT;
l = ['ab', 'xc', 'abb', 'abed', 'sdfdg', 'abfdsdg', 'xccc']
res = [string for string in l if sum(not string.startswith(prefix) for prefix in l) == len(l)-1]
答案 3 :(得分:4)
import thread
import math
import multiprocessing
list = ['ab', 'xc', 'abb', 'abed', 'sdfdg', 'abfdsdg', 'xccc']
def get_results(list, thread_num, num_of_threads):
result = []
part_size = int(math.ceil(len(list) * 1.0 / num_of_threads))
for element in list[part_size * thread_num: part_size * (thread_num + 1)]:
is_prefixed = False
for possible_prefix in list:
if element is not possible_prefix and element.startswith(possible_prefix):
is_prefixed = True
if not is_prefixed:
result.append(element)
return result
num_of_threads = multiprocessing.cpu_count()
results = []
for t in xrange(num_of_threads):
thread.start_new_thread(lambda list: results.extend(get_results(list, t, num_of_threads)), (list,))
测试得好!
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="MyBehavior">
<useRequestHeadersForMetadataAddress></useRequestHeadersForMetadataAddress>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="TestProject.Implementations.AuthenticateUser,TestProject"/>
<serviceCertificate findValue="localhost" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="TestProject.Implementations.ServiceCustom" behaviorConfiguration="MyBehavior">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="SampleServiceBinding" contract="TestProject.Interfaces.IServiceCustom"></endpoint>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"></endpoint>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="SampleServiceBinding">
<security mode ="Message">
<message clientCredentialType="UserName"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
答案 4 :(得分:3)
from collections import Counter
def filter_list(mylist):
longest_string = len(max(mylist, key=len))
set_list = [set(filter(lambda x: len(x) == i, mylist))
for i in range(1, longest_string)]
def unique_starts_with_filter(string):
for i in range(1, len(string)):
if string[:i] in set_list[i-1]: return False
return True
cn = Counter(mylist)
mylist = filter(lambda x: cn[x] == 1, mylist)
return filter(unique_starts_with_filter, mylist)
再次编辑样式和非常小的优化
答案 5 :(得分:3)
解决方案1 (使用LinkedList)
这是一个非常简单的解决方案,使用排序(O(n * log(n))
)和LinkedList
- 迭代(O(n)
)和删除元素(O(1)
)。如果对初始数据进行排序,则将按照以下方式对元素进行排序:另一个元素的最长前缀元素将与后者相邻。因此可以删除该元素。
以下是过滤掉已排序的LinkedList
:
def filter_out(the_list):
for element in the_list:
if element.prev_node and element.get_data().startswith(element.prev_node.get_data()):
the_list.remove(element)
return the_list
并像这样使用它:
linked_list = LinkedList(sorted(l))
filter_out(linked_list)
然后,您的linked_list
将包含已过滤的数据。
此解决方案将采用O(n * log(n))
以下是LinkedList
的实施:
class Node(object):
def __init__(self, data=None, next_node=None, prev_node=None):
self.data = data
self._next_node = next_node
self._prev_node = prev_node
def get_data(self):
return self.data
@property
def next_node(self):
return self._next_node
@next_node.setter
def next_node(self, node):
self._next_node = node
@property
def prev_node(self):
return self._prev_node
@prev_node.setter
def prev_node(self, node):
self._prev_node = node
def __repr__(self):
return repr(self.get_data())
class LinkedList(object):
def __init__(self, iterable=None):
super(LinkedList, self).__init__()
self.head = None
self.tail = None
self.size = 0
if iterable:
for element in iterable:
self.insert(Node(element))
def insert(self, node):
if self.head:
self.tail.next_node = node
node.prev_node = self.tail
self.tail = node
else:
self.head = node
self.tail = node
self.size += 1
def remove(self, node):
if self.size > 1:
prev_node = node.prev_node
next_node = node.next_node
if prev_node:
prev_node.next_node = next_node
if next_node:
next_node.prev_node = prev_node
else:
self.head = None
self.tail = None
def __iter__(self):
return LinkedListIter(self.head)
def __repr__(self):
result = ''
for node in self:
result += str(node.get_data()) + ', '
if result:
result = result[:-2]
return "[{}]".format(result)
class LinkedListIter(object):
def __init__(self, start):
super(LinkedListIter, self).__init__()
self.node = start
def __iter__(self):
return self
def next(self):
this_node = self.node
if not this_node:
raise StopIteration
self.node = self.node.next_node
return this_node
解决方案2 (使用设置)
如果算法不需要稳定,即结果列表不需要保持元素的原始顺序,这里是使用set
的解决方案。
所以让我们做一些定义:
n
- 列表的大小,即元素数量
m
- 列表中字符串元素的最大可能长度
首先,从原始set
inter
中初始化新的list
l
:
inter = set(l)
通过这个我们将删除所有重复的元素,这将简化我们的进一步工作。此外,此操作的平均复杂度为O(n)
,最差情况下为O(n^2)
。
然后再制作一个空set
,我们会保留结果:
result = set()
现在让我们检查每个元素,我们的inter
集合中是否有后缀:
for elem in inter: # This will take at most O(n)
no_prefix = True
for i in range(1, len(elem)): # This will take at most O(m)
if elem[:i] in inter: # This will take avg: O(1), worst: O(n)
no_prefix = False
continue
if no_prefix:
result.add(elem) # This will take avg: O(1), worst: O(n)
所以现在你已经在result
得到了你想要的东西。
最后和核心步骤的平均值为O(n * (1 * m + 1)) = O(n * m)
,最差情况下为O(n * (m * n + n)) = O(n^2 * (m + 1))
,因此如果m
与n
相比无关紧要,那么您的{{1}在最差的情况下,平均值为O(n)
。
复杂性是根据Python provides for the set
data structure计算的。要进一步优化算法,您可以实施自己的O(n ^ 2)
并获得tree-based set
复杂度。
答案 6 :(得分:3)
我相信以下内容很可能是效率最高的。
from sortedcontainers import SortedSet
def prefixes(l) :
rtn = SortedSet()
for s in l:
rtn.add(s)
i = rtn.index(s)
if (i > 0 and s.startswith(rtn[i-1])):
rtn.remove(s)
else :
j = i+1
while (j < len(rtn) and rtn[j].startswith(s)):
j+=1
remove = rtn[i+1:j]
for r in remove:
rtn.remove(r)
return list(rtn)
我认为最重要的情况可能是输入文件很长,输出文件要小得多。此解决方案避免将整个输入文件保存在内存中。如果输入文件已排序,则它永远不会保留比最终返回文件更长的rtn参数。此外,它还演示了&#34;维护一个对目前看到的数据有效的解决方案的模式,并将此解决方案扩展为对每个新数据片段有效&#34;。这是一个熟悉的好模式。
答案 7 :(得分:2)
使用reduce函数的解决方案:
def r(a, b):
if type(a) is list:
if len([z for z in a if b.startswith(z)]) == 0:
a.append(b)
return a
if a.startswith(b):
return b
if b.startswith(a):
return a
return [a, b]
print reduce(r, l)
可能[z for z in a if b.startswith(z)]
部分可以进一步优化。
答案 8 :(得分:2)
您可以尝试这个简短的解决方案。
import re
l = ['ab', 'xc', 'abb', 'abed', 'sdfdg', 'abfdsdg', 'xccc']
newl=[]
newl.append(l[0])
con=re.escape(l[0])
for i in l[1:]:
pattern=r"^(?!(?:"+con+r")).*$"
if re.match(pattern,i):
newl.append(i)
con=con+"|"+re.escape(i)
print newl
编辑:对于长列表,请使用
import re
l = ['ab', 'xc', 'abb', 'abed', 'sdfdg', 'abfdsdg', 'xccc']
newl=[]
newl.append(l[0])
con=re.escape(l[0])
for i in l[1:]:
for x in re.split("\|",con):
pattern=r"^(?="+x+r").*$"
if re.match(pattern,i):
break
else:
newl.append(i)
con=con+"|"+re.escape(i)
print newl