gpt4 book ai didi

python - 根据不同的标准规则检查列表

转载 作者:太空宇宙 更新时间:2023-11-04 09:16:10 26 4
gpt4 key购买 nike

给定一个项目列表,我想创建一个函数来检查它是否符合特定条件并返回 true 或 false。

这是标准和预期输出的示例:

    #the to check against with criteria[1]
langList = ['spanish','english','russian','persian']

criteria = ['any'] #matches any language
result: match

#langList does not contain one or all
criteria = ['any-but-or',[english,chinese]]
result: no match

#langList does not contain all
criteria = ['any-but-and',[english,chinese]]
result: match

#langList contains one or all
criteria = ['any-with-or',[english,chinese]]
result: match

#langList contains all
criteria = ['any-with-and',[english,chinese]]
result: no match

#langList contains one or all and no others
criteria = ['only-with-or',[english,chinese]]
result: no match

#langList contains all and no others
criteria = ['only-with-and',[english,chinese]]
result: no match

执行此操作的最佳方法是什么?我的想法如下所示,但我还没有掌握列表理解,我认为这是这里的关键。

    def check_criteria_match(criteria, languageList):

rule = criteria[0]
criteriaLanguages = criteria[1]
match = True

if rule != 'any':
continue
elif rule = 'any-but-or' #check languageList:
match = False; break

#[...]

return match

编辑:基于 Praveen Gollakota 的 answer , 这是最后一个函数,她是不是很漂亮:)

def check_rule(rule, o, p):
# o = original, p = pattern
if rule == 'any':
return True
elif rule == 'any-but-or':
return not bool(set(p)-set(o))
elif rule == 'any-but-and':
return len(set(p)-set(o)) != 0
elif rule == 'any-with-or':
return len(set(p)-set(o)) <= 1
elif rule == 'any-with-and':
return len(set(p)-set(o)) == 0
elif rule == 'only-with-or':
return len(set(o)-set(p)) <= 1
elif rule == 'only-with-and':
return len(set(o)-set(p)) == 0

最佳答案

您想进行成员资格测试,sets 是合适的数据结构,set 操作运行良好。

您可以像这样使用集合和 lambda 函数来构建基于规则的调度程序。

>>> rule_checker = {'any': lambda o, p: True, 
... 'any-but-or': lambda o, p: not bool(set(p) - set(o)),
... 'any-but-and': lambda o, p: len(set(p) - set(o)) != 0,}

>>> lang_list = ['spanish','english','russian','persian']
>>> rule_checker['any-but-and'](lang_list, ['english','chinese'])
True
>>> rule_checker['any-but-or'](lang_list, ['english','chinese'])
False

当然,您需要在其中添加其余规则。

编辑:您也可以像这样在函数中编写规则。

>>> def check_rule(rule, o, p):
... # o = original, p = pattern
... if rule == 'any':
... return True
... elif rule == 'any-but-or':
... return not bool(set(p)-set(o))
... elif rule == 'any-but-and':
... return len(set(p)-set(o)) != 0
...
>>> check_rule('any-but-and', lang_list, ['english','chinese'])
True

关于python - 根据不同的标准规则检查列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9228982/

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