首页 > 解决方案 > python中的'in'运算符功能

问题描述

我需要删除string1. string2在这里string1string2只有小写字符 az 具有给定的条件,string1每次的长度都会更大。

我正在使用in运算符:

def removeChars (string1, string2):
    for char in string2:
        if char in string1:
            string1 = string1.replace(char, '')
    return string1

但我在 Stack Overflow 上读到了一个答案,上面写着:

对于 list、tuple、set、frozenset、dict 或 collections.deque 等容器类型,表达式x in y等效于any(x is e or x == e for e in y).

这意味着操作员在幕后in使用循环。for

所以我的问题是,在for我的代码循环中,我是否应该考虑使用嵌套for循环,因为操作员在后台in使用循环?for如果是,这个程序的时间复杂度是多少?

标签: pythontime-complexity

解决方案


in does not necessarily use loops behind the scenes. For example:

r = range(100000000000)
print(333 in r)  # prints True immediately without looping

If you were to loop r it will take quite a long time, so clearly that doesn't happen.

in basically calls (behind the scenes) the object's __contains__ method. For some iterators it will in fact "loop" through everything but that's not always the case.

This example is basically the same as calling:

r.__contains__(333)

As pointed out in comments - the str objects specifically have a smarter algorithm than just plain loops, as you can see here

Also see example answer here

And see the documentation here

Because the real world scenario would probably mean that string1 can be arbitrarily long, but the characters to be removed would be a finite and small set, it will probably be much more efficient to just add up all the characters that aren't in string2. Something like this:

def removeChars (string1, string2):
    result = ''
    for char in string1:
        if char not in string2:
            result += char
    return result

This will involve looping over string1 just once, but multiple checks against string2 using in. This can be further simplified (to avoid += loop over the result):

def removeChars (string1, string2):
    return ''.join(char for char in string1 if char not in string2)

推荐阅读