在另一个字符串中查找字符串的所有字母

时间:2018-04-23 07:06:06

标签: python

我正在开展一个项目,找到一个单词的所有字谜和许多其他单词。 为此我需要一个带2个字符串的函数,如果str1的所有字母都在str2中,则返回True。

我制作了这段代码:

def almost_anagram(str1, str2):
    tmp = list(str2)
    for i in str1:
            if i in tmp:
                    tmp.remove(i)
            else:
                    return False
    return True

例如:

 almost_anagram("OLLE", "HELLO") = True
 almost_anagram("OOLE", "HELLO") = False

但有没有更好/更快的方法呢?

4 个答案:

答案 0 :(得分:4)

您可以使用Counter,它基本上代表一套多套:

import collections

def almost_anagram(word1, word2):
    counter1 = collections.Counter(word1)
    counter2 = collections.Counter(word2)
    return counter1 - counter2 == {}
    # alternatively:
    # return all(counter2[k] >= v for k, v in counter1.items())
    # return counter1 & counter2 == counter1

如果return counter1 < counter2支持使用Counter类似集合进行子集测试,则代码可以简化为<,但遗憾的是它没有。

输出:

>>> almost_anagram("OLLE", "HELLO")
True
>>> almost_anagram("OOLE", "HELLO")
False

答案 1 :(得分:1)

Switch-sfx2list comprehension一起使用应该更快。

<强>实施例

all

<强>输出:

def almost_anagram(str1, str2):
    return all(str2.count(i) >=  str1.count(i) for i in set(str1))

print(almost_anagram("OLLE", "HELLO"))
print(almost_anagram("OOLE", "HELLO"))

答案 2 :(得分:1)

使用collections.Counter对象立即获取字母数:

import collections    

def almost_anagram(str1, str2):
    str1_cnt, str2_cnt = collections.Counter(str1), collections.Counter(str2)
    return all(k in str2_cnt and str2_cnt[k] == v 
               for k,v in str1_cnt.items())

测试:

print(almost_anagram("OLLE", "HELLO"))  # True
print(almost_anagram("OOLE", "HELLO"))  # False

答案 3 :(得分:0)

我更喜欢使用count()函数,而不需要将字符串转换为列表:

def almost_anagram(str1, str2):
    for i in str1:
        if(str1.count(i)==str2.count(i)):
            pass
        else:
            return False
    return True

print(almost_anagram('olle','hello'))
print(almost_anagram('oole','hello')) 

输出:

True
False          
相关问题