python,清洗列表

2 投票
5 回答
5804 浏览
提问于 2025-04-16 20:10

我在尝试清理一个Python列表,我可以删除完全匹配的字符串。那怎么删除部分匹配的呢?

exclude = ['\n','Hits','Sites','blah','blah2','partial string','maybe here']
newlist = []
for item in array:
    if item not in exclude:
        newlist.append(item)

这里的问题是“item not in exclude”... 这个是完全匹配的。

我应该使用下面的方法吗:

s = "This be a string"
if s.find("is") == -1:
    print "No 'is' here!"
else:
    print "Found 'is' in the string."

其实我自己已经回答了自己的问题 :) 我想知道有没有其他的运算符可以替代'in'?

谢谢

5 个回答

1
exclude = ['\n','Hits','Sites','blah','blah2','partial string','maybe here']
newlist = []
for item in array:
        ok = True
        for excItem in exclude:
                if excItem in item: 
                    ok = False
                    break
        if ok: newlist.append(item)

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

2

试试下面这个生成器:

def remove_similar(array, exclude):
    for item in array:
        for fault in exclude:
            if fault in item:
                break
        else:
            yield item
1

这就是你在找的东西吗?

blacklist = ['a', 'b', 'c']
cleaned = []
for item in ['foo', 'bar', 'baz']:
    clean = True
    for exclude in blacklist:
        if item.find(exclude) != -1:
            clean = False
            break
    if clean:
        cleaned.append(item)
print cleaned # --> ['foo']

撰写回答