python - python中的'in'运算符功能
问题描述
我需要删除string1
. string2
在这里string1
,string2
只有小写字符 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
如果是,这个程序的时间复杂度是多少?
解决方案
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)
推荐阅读
- ruby - 用锚点回到指定点
- xamarin - uwp 中密码框的背景
- angular - SSR Angular Universal,apollo-angular 应用程序中的“ApolloError:网络错误”
- java - 找不到适合 jdbc:oracle:thin:@localhost:1521:xe 错误的驱动程序
- json - 如何在 Postgres 中从 json 中选择查询
- c++ - Parameter pack to parameter pack mapping
- java - 关闭 Mongodb Changestream 导致异常
- javascript - Java加密转javascript解密AES、CryptoJS、CTR
- java - TestNG vs Junit vs Mockito?
- ios - iOS13:PopoverPresentationController - 箭头一侧的边框缺失