我有一个列表l = ['abcdef', 'abcd', 'ghijklm', 'ghi', 'xyz', 'pqrs']
我想删除从同一个子字符串开始的元素,如果它们存在(在这种情况下'abcd'
和'ghi'
)。
N. B:在我的情况下,我知道“重复”的元素,如果存在的话,只能是‘ABCD’或‘t’。
为了删除它们,我使用了这个:
>>> l.remove('abcd') if ('abcdef' in l and 'abcd' in l) else l
>>> l.remove('ghi') if ('ghijklm' in l and 'ghi' in l) else l
>>> l
>>> ['abcdef', 'ghijklm', 'xyz', 'pqrs']
有没有更有效(或更自动化)的方法来做到这一点?
最佳答案
可以在线性时间和O(n*m m2)内存(其中m是元素的长度)中执行此操作:
prefixes = {}
for word in l:
for x in range(len(word) - 1):
prefixes[word[:x]] = True
result = [word for word in l if word not in prefixes]
遍历每个单词,并创建一个字典,其中包含每个单词的第一个字符,然后是前两个字符,然后是第三个字符,一直到单词的所有字符,最后一个字符除外然后再次遍历列表,如果某个单词出现在该词典中,则它是列表中其他单词的较短子集