Jac*_*ack 0 python string python-itertools
比如我有
x = "dsjcosnag"
y = "dog"
print(checkYinX(y,x))
>>true
Run Code Online (Sandbox Code Playgroud)
所以我想我需要使用while循环作为y中每个字母的计数器,然后我可以使用itetools循环遍历每个x,每个循环它会检查x == y,如果它是它会删除它然后检查o中的下一个字母.
有更简单的方法吗?
使用collections.Counter()
转换x
和y
到多套,然后减去,看看是否所有的y
的信中可以找到x
:
from collections import Counter
def checkYinX(y, x):
return not (Counter(y) - Counter(x))
Run Code Online (Sandbox Code Playgroud)
减去多个集合会在它们的计数降为0时删除字符.如果这导致一个空的多集,它就会变成False
一个布尔上下文,就像所有'空'python类型一样.如果是这样的话not
就把它变成True
了.
演示:
>>> x = "dsjcosnag"
>>> y = "dog"
>>> print(checkYinX(y,x))
True
>>> print(checkYinX('cat',x))
False
Run Code Online (Sandbox Code Playgroud)