Skip to main content
 首页 » 编程设计

python之根据部分字符串去除冗余字符串

2025年05月04日15hnrainll

我有一组查询,其中一些只是最终搜索字符串的一部分。我需要从很长的查询集合中清除部分字符串。是否有一种快速的方法可以在像这样的数百万个集合中执行此操作?

t = {u'house prices', 
 u'how ', 
 u'how man', 
 u'how many animals go ex', 
 u'how many animals go extinted eac', 
 u'how many animals go extinted each ', 
 u'how many species go', 
 u'how many species go extin', 
 u'how many species go extinet each yea', 
 u'how many species go extinet each year?'} 

我只想保留:

t = {u'house prices', 
 u'how many species go extinet each year?', 
 u'how many animals go extinted each '} 

这是来自@Alex Hall 的解决方案,经过编辑以捕获最终字符串('-+-' 的连接就是这样做的)

# Print out the unique strings 
q = sorted(list(t)) + ['-+-'] 
for i in range(len(q) - 1): 
    if not q[i+1].startswith(q[i]): 
        print i, q[i] 

请您参考如下方法:

对集合进行排序以生成列表 q,然后遍历它并构建一个新的元素列表,其中 不是 q[i+1].startswith(q[i]) 。应该相当好地完成这个技巧。