Python计数器和字典交集示例
当需要演示计数器和字典的交集时,可以使用计数器和字典。
以下是相同的演示-
示例
from collections import Counter
def make_string(str_1,str_2):
dict_one = Counter(str_1)
dict_two = Counter(str_2)
result = dict_one & dict_two
return result == dict_one
string_1 = 'Hi Mark'
string_2 = 'how are yoU'
print("第一个字符串是:")
print(string_1)
print("第二个字符串是:")
print(string_2)
if (make_string(string_1,string_2)==True):
print("It is possible")
else:
print("It is not possible")输出结果第一个字符串是: Hi Mark 第二个字符串是: how are yoU It is not possible
解释
导入所需的包。
定义了一个方法,它接受两个字符串,并将它们转换为一个计数器。
然后将其分配给字典。
在字典外定义了两个字符串,通过传递这两个字符串来调用方法。
取决于函数返回“真”还是“假”的相关输出显示在控制台上。