在 Python 中使用 OrderedDict( ) 检查字符串中字符的顺序
当需要检查字符串中字符的顺序时,可以使用'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("字符串是 ") print(my_input) print("输入模式是 ") print(input_pattern) print(check_order(my_input,input_pattern))输出结果
字符串是 Hi Mark 输入模式是 Ma The order of pattern is correct
解释
导入所需的包。
定义了一个名为“check_order”的方法,它接受两个参数。
使用“fromkeys”方法创建有序字典。
模式的长度初始化为0。
如果键等于模式,则模式的长度增加。
如果pattern长度与当前长度相同,则说明顺序正确,否则顺序错误。
相关消息作为输出显示在控制台上。