【问题标题】:How to pass (string) conditions as function arguments? [duplicate]如何将(字符串)条件作为函数参数传递? [复制]
【发布时间】:2021-12-28 11:30:04
【问题描述】:

我想将 3 个条件传递给函数“check”以应用于 str1,在这种情况下输出应该是 [False, False, True]:

def check(conditions):
    str1 = '/'
    print(conditions)

check(conditions=[str1.find('//www.fao.org')!=-1, str1.find('//fao.org')!=-1, str1[0]=='/'])

但是,在调用该函数之前,它会运行一个错误:

NameError: name 'str1' is not defined

因为这意味着条件在函数检查执行之前就已经执行了,我怎样才能将这些条件作为参数传递?

【问题讨论】:

  • 变量 str1 在这种情况下在函数范围内。如果需要,可以将其移至全局范围。
  • 如果你想定义一个针对 str1 进行评估的函数,请将其定义为...好吧,一个函数,所以check() 可以将str1 传递给它.

标签: python function conditional-statements


【解决方案1】:

传递一个函数列表来调用str1

def check(conditions):
    str1 = '/'
    for f in conditions:
        print(f(str1))

check(conditions=[lambda x: x.find('//www.fao.org') != -1, lambda x: x.find('//fao.org') != -1, lambda x: x[0] == '/'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 2020-01-18
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多