gpt4 book ai didi

python - 匹配字符串的字符

转载 作者:行者123 更新时间:2023-11-30 22:21:34 26 4
gpt4 key购买 nike

如果我调用 matcher.match('bad') 它应该返回提供的列表中存在的 'bad' 的所有排列的列表。在此示例中,输出将为['abd']。到目前为止,这是我尝试过的,但我似乎无法匹配这个模式。

class Matcher():
def __init__(self, string_list):
self.string_list = string_list

def match(self, string_match):
matched_list = [string for string in string_list if string_match in string]
return matched_list

string_list = ['abd', 'abdd', 'fret', 'gilk', 'lokm']
matcher = Matcher(string_list)
print(matcher.match('abd'))

最佳答案

这是一个 O(n log n) 解决方案:

string_list = ['abd', 'abdd', 'fret', 'gilk', 'lokm']

my_str = 'bad'

[x for x in string_list if sorted(my_str) == sorted(x)] # ['abd']

关于python - 匹配字符串的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48621161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com