Skip to main content
 首页 » 编程设计

python之如何删除列表中的起始词

2025年05月04日64thcjp

给定一个包含一些“inception”词的列表,如何删除 inception 词?如何找到更大的起始词?

让我们将起始词定义为出现在同一列表中的较大词的一部分的词。

任务:

To make it very clear, if a list contains ['a', 'b', 'a b c'], removes 'a' and 'b' because there is an element that contains 'a' and 'b' that is bigger itself.

示例 1,[in]:

[u'dose rate', u'object', u'dose', u'rate', u'computation'] 

[输出]:

[u'dose rate', u'object',u'computation'] 

示例 2,[in]:

[u'shift', u'magnetic', u'system', u'magnetic sensor', u'phase shift', u'phase', u'output', u'sensor', u'sensing', u'sensor system'] 

由于存在“magnetic”、“sensor”、“system”、“magnetic sensor”和“sensor system”,我们可以:

期望的输出,[out]:

[u'system', u'magnetic sensor', u'phase shift', u'output', u'sensing'] 

或[出]:

[u'magnetic'u'phase shift', u'output', u'sensing', u'sensor system'] 

我已尝试以下操作,但未获得所需的输出:

ls = [u'dose rate', u'object', u'dose', u'rate', u'computation'] 
>>> set([i for i in ls for j in ls if i!=j or i not in j]) 
set([u'dose rate', u'object', u'rate', u'computation', u'dose']) 
>>> set([j for i in ls for j in ls if i!=j or i not in j]) 
set([u'rate', u'object', u'dose rate', u'computation', u'dose']) 
>>> set([j for j in ls for i in ls if i!=j or i not in j]) 
set([u'dose rate', u'object', u'rate', u'computation', u'dose']) 

请您参考如下方法:

所以为了满足第一个例子,你可以这样做,

>>> words = [u'dose rate', u'object', u'dose', u'rate', u'computation'] 
>>> [w1 for w1 in words if not any(w1 in w2 for w2 in words if w2 != w1)] 
[u'dose rate', u'object', u'computation'] 

但是你的第二个例子表明你的要求有点复杂。您不能多次使用同一个小词来形成一个字符串。

不幸的是,一条线是不可能的。尝试类似的东西,

def remove_comprising(words): 
    seen = set() 
    result_words = [] 
    for word in words: 
        for small_word in words: 
            if small_word in word and small_word != word: 
                if small_word in seen: 
                    word = word.replace(small_word, '') 
                else: 
                    seen.add(small_word) 
        result_words.append(word) 
    return [word.strip() for word in result_words if word not in seen] 

然后我们得到两个示例 1 的正确结果,

>>> words = [u'dose rate', u'object', u'dose', u'rate', u'computation'] 
>>> remove_comprising(words) 
[u'dose rate', u'object', u'computation'] 

和例子2,

>>> words = [u'shift', u'magnetic', u'system', u'magnetic sensor', u'phase shift', u'phase', u'output', u'sensor', u'sensing', u'sensor system'] 
>>> remove_comprising(words) 
[u'magnetic sensor', u'phase shift', u'output', u'sensing', u'system']