【问题标题】:python, cleaning a listpython,清理列表
【发布时间】:2011-09-21 10:17:18
【问题描述】:

尝试清理 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' 的操作数?

谢谢

【问题讨论】:

  • 不是很清楚,你想要什么。另外,您在上面的代码中定义的array 是什么?
  • 这显然取决于“部分匹配”的定义:什么被认为是匹配,什么不是?
  • string.find(s, sub[, start[, end]])

标签: python string


【解决方案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']

【讨论】:

    【解决方案2】:

    怎么样:

    all( s.find(e) == -1 for e in exclude )
    

    如果在s 中找不到任何排除字符串作为子字符串,则返回True


    如果部分是指se 的子字符串,那么:

    not any( e.find(s) != -1 for e in exclude )
    

    如果在exclude 的任何字符串中都没有找到s 作为子字符串,则返回True

    【讨论】:

    • 部分匹配呢?我希望能够捕获完全匹配的字符串,部分匹配
    • 如果他出于某种原因确实需要该列表,则可以轻松修改以上内容以生成它。
    • 无法将其放入 python :)
    【解决方案3】:

    改用以下生成器:

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

    【讨论】:

    • 是的,但这只会删除完全匹配...我将如何搜索部分匹配?
    • 您可能想要测试它:list(remove_similar(['a', 'b', 'ab', 'c', 'ac', 'bc', 'abc'], ['a'])) 这将返回列表['b', 'c', 'bc']。这就是你想要的吗?
    【解决方案4】:
    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)
    

    【讨论】:

    • 谢谢!但这不匹配部分内容,只匹配完全匹配......我将如何做到这一点?
    • +1 因为考虑到“部分匹配”的模糊性,它已经足够接近 OP 想要的了。
    【解决方案5】:

    我不确定你在这里问什么。是否要过滤掉array 中作为exclude 元素的子字符串的所有元素?如果是这样,您可以更换您的线路

    if item not in exclude:
    

    类似的东西

    if not any(item in e for e in exclude):
    

    【讨论】:

    • 嗯...我试图捕捉部分和完全匹配...如果这有意义:)
    • 字符串a 是字符串b 的“部分匹配”是什么意思?我将其解释为“ab 的子字符串”。我想其他人也对此感到困惑。
    • 我想做的是:string.find(s)
    • 我希望循环遍历排除列表并找到任何部分匹配项,而不是完全匹配项
    猜你喜欢
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多