首页 > 解决方案 > 如何从python中的列表字符串列表中删除一个元素,该元素是另一个元素的子字符串?

问题描述

我有一个列表字符串列表,如下所示:

[["['rest']"],["['look']"],["['rest','look']"],["['resting','look]"],["['rest','resting','look','looked','it','spit']"]]

必须删除作为另一个元素的子字符串的所有元素。例如元素['rest']and['look']已经存在于列表元素['rest','look']and['rest','resting','look','looked','it','spit']中,因此必须从最终列表中删除它们。但是 element['rest','look']不是 的子字符串['rest','resting','look','looked','it','spit'],因为较大的列表元素'resting'介于'rest'和之间'look',因此不应将其删除。同样,['resting','look']是 的子字符串['rest','resting','look','looked','it','spit'],因此必须将其删除。

我试过这个:

x = [['rest'],['look'],['rest','look'],['resting','look'],['rest', 'resting', 'look', 'looked', 'it', 'spit']]

res=[]

found=0

for i in x:
   for item in i:
     for j in x:
          for item1 in j:
            if item == item1:
               found=1
     if found==0:
          res.append(item)

print res

我得到的输出是一个空列表。所需的输出是:

[["['rest','look']"], ["['rest','resting','look','looked','it','spit']"]]

标签: pythonlist

解决方案


推荐阅读