我有一个要从另一个列表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']
答案 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)