python从字符串列表中删除子串

时间:2014-03-06 10:36:32

标签: python list substring

我有list l=['abc','abcdef','def','defdef','polopolo'] 我试图删除其超链接已经在列表中的字符串。在这种情况下,结果应为:

['abcdef','defdef','polopolo']

我写了代码:

l=['abc','abcdef','def','defdef','polopolo']
res=['abc','abcdef','def','defdef','polopolo']
for each in l:
    l1=[x for x in l if x!=each]
    for other in l1:
        if each in other:
            res.remove(each)

但它似乎无法奏效。我已经读过,迭代它时我们无法从列表中删除。因此复制res。,而l是我的原始列表。     提前致谢。

1 个答案:

答案 0 :(得分:4)

l=['abc','abcdef','def','defdef','polopolo']
print [j for i, j in enumerate(l) if all(j not in k for k in l[i + 1:])]
# ['abcdef', 'defdef', 'polopolo']

我们可以通过在

之前对列表进行排序来加快速度
l = sorted(l, key = len)
print [j for i, j in enumerate(l) if all(j not in k for k in l[i + 1:])]

作为@Ashwini Chaudhary mentions in the comments,如果要保留重复的字符串,则可以执行此操作

l = ['abc','defghi' 'abcdef','def','defdef','defdef', 'polopolo']
l = sorted(l, key = len)
print [j for i,j in enumerate(l) if all(j == k or (j not in k) for k in l[i+1:])]
# ['defdef', 'defdef', 'polopolo', 'defghiabcdef']