如何在Python中的列表中查找或删除子字符串列表

时间:2019-02-26 06:48:21

标签: python

我有一个要从另一个列表mylist

中删除的子字符串列表。
mylist = ['abc123', 'def456', 'ghi789','ghi123']

sub = ['123','456']
print ([s for s in mylist if sub[j] in s for j in sub])

这给出了错误。还有其他方法可以找到这个。

预期输出:

['abc123','ghi123','def456']

2 个答案:

答案 0 :(得分:3)

看起来像您需要的

mylist = ['abc123', 'def456', 'ghi789','ghi123']
sub = ['123','456']

print ([i for i in mylist for j in sub if j in i])

输出:

['abc123', 'def456', 'ghi123']

答案 1 :(得分:0)

您可以为此使用正则表达式

import re

mylist = ['abc123', 'def456', 'ghi789', 'ghi123']

sub = ['123', '456']
for item in mylist:
    m = re.match(r"([a-zA-Z]+)([0-9]+)", item)
    if m.group(2) not in sub:
        mylist.remove(item)
    print(mylist)