使用 OrderedDict( ) 檢查 Python 字串中字元的順序
如果需要檢查字串中字元的順序,可以使用 “OrderedDict” 方法。
以下是演示:
示例
from collections import OrderedDict
def check_order(my_input, my_pattern):
my_dict = OrderedDict.fromkeys(my_input)
pattern_length = 0
for key,value in my_dict.items():
if (key == my_pattern[pattern_length]):
pattern_length = pattern_length + 1
if (pattern_length == (len(my_pattern))):
return 'The order of pattern is correct'
return 'The order of pattern is incorrect'
my_input = 'Hi Mark'
input_pattern = 'Ma'
print("The string is ")
print(my_input)
print("The input pattern is ")
print(input_pattern)
print(check_order(my_input,input_pattern))輸出
The string is Hi Mark The input pattern is Ma The order of pattern is correct
說明
匯入所需包。
定義一個名為 “check_order” 的方法,它接受兩個引數。
使用 “fromkeys” 方法建立一個有序字典。
模式的長度初始化為 0。
如果鍵等於模式,則增加模式的長度。
如果模式的長度與當前長度相同,則表示順序正確,否則順序錯誤。
在控制檯上以輸出形式顯示相關訊息。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP