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("The first string is :")
print(string_1)
print("The second string is :")
print(string_2)
if (make_string(string_1,string_2)==True):
   print("It is possible")
else:
   print("It is not possible")

輸出

The first string is :
Hi Mark
The second string is :
how are yoU
It is not possible

說明

  • 匯入了所需的包。

  • 定義了一個方法,該方法獲取兩個字串,並將它們轉換成一個計數器。

  • 然後將其分配給一個字典。

  • 在字典之外,定義了兩個字串,並透過傳遞這兩個字串呼叫該方法。

  • 根據函式返回“True”或“False”,在控制檯上顯示相關輸出。

更新於:2021 年 4 月 17 日

231 次瀏覽

職業起跑

透過完成課程獲得認證

開始
廣告
© . All rights reserved.