动态地循环遍历Python中函数的函数列表

jhu*_*ub1 9 python loops list

我想看看是否可以在函数中运行函数列表.我能找到的最接近的东西是循环整个模块.我只想使用预先选择的功能列表.

这是我原来的问题:

  1. 给定一个字符串,检查每个字母以查看是否满足5个测试中的任何一个.
  2. 如果至少1个字母通过检查,则返回True.
  3. 如果字符串中的所有字母都未通过检查,则返回False.
  4. 对于字符串中的每个字母,我们将检查这些函数:isalnum(),isalpha(),isdigit(),islower(),isupper()
  5. 每个测试的结果应该打印到不同的行.

样本输入

    qA2
Run Code Online (Sandbox Code Playgroud)

样本输出(必须打印到单独的行,如果至少一个字母通过则为True,否则为每个测试的所有字母都失败):

    True
    True
    True
    True
    True
Run Code Online (Sandbox Code Playgroud)

我写了一个测试.当然我可以写出5组不同的代码,但这看起来很难看.然后我开始想知道我是否可以循环完成他们要求的所有测试.

仅一个测试的代码:

    raw = 'asdfaa3fa'
    counter = 0
    for i in xrange(len(raw)):
        if raw[i].isdigit() == True: ## This line is where I'd loop in diff func's
            counter = 1
            print True
            break
    if counter == 0:
        print False
Run Code Online (Sandbox Code Playgroud)

我尝试使用所有测试运行循环失败:

    raw = 'asdfaa3fa'
    lst = [raw[i].isalnum(),raw[i].isalpha(),raw[i].isdigit(),raw[i].islower(),raw[i].isupper()]
    counter = 0
    for f in range(0,5):
        for i in xrange(len(raw)):
            if lst[f] == True: ## loop through f, which then loops through i
                print lst[f] 
                counter = 1
                print True
        break
        if counter == 0:
    print False
Run Code Online (Sandbox Code Playgroud)

那么如何修复此代码以实现其中的所有规则?


使用来自所有注释的信息 - 此代码满足上述规则,同时动态循环遍历每个方法.

    raw = 'ABC'
    functions = [str.isalnum, str.isalpha, str.isdigit, str.islower,  str.isupper]

    for func in functions:
        print any(func(letter) for letter in raw)
Run Code Online (Sandbox Code Playgroud)

getattr方法(我认为这被称为内省方法?)

    raw = 'ABC'

    meths = ['isalnum', 'isalpha', 'isdigit', 'islower', 'isupper']
    for m in meths: 
        print any(getattr(c,m)() for c in raw)
Run Code Online (Sandbox Code Playgroud)

列表理解方法:

    from __future__ import print_function ## Changing to Python 3 to use print in list comp

    raw = 'ABC'
    functions = [str.isalnum, str.isalpha, str.isdigit, str.islower, str.isupper]
    solution = [print(func(raw)) for func in functions]
Run Code Online (Sandbox Code Playgroud)

gow*_*ath 9

循环浏览函数列表的方式略有不同.这将是一种有效的方法.您需要存储在列表中的函数是str.funcname给出的通用字符串函数.一旦你有了这些函数列表,就可以使用for循环遍历它们,并将其视为普通函数!

raw = 'asdfaa3fa'
functions = [str.isalnum, str.isalpha, str.isdigit, str.islower,  str.isupper]  # list of functions

for fn in functions:     # iterate over list of functions, where the current function in the list is referred to as fn
    for ch in raw:       # for each character in the string raw
        if fn(ch):        
            print(True)
            break
Run Code Online (Sandbox Code Playgroud)

样本输出:

Input                     Output
===================================
"qA2"         ----->      True True True True True
"asdfaa3fa"   ----->      True True True True
Run Code Online (Sandbox Code Playgroud)

另外我注意到你似乎使用索引进行迭代,这让我觉得你可能会来自像C/C++这样的语言.for循环结构在python中非常强大,所以我会读它(y).

上面是一个更加pythonic的方式来做到这一点,但作为一个学习工具,我写了一个工作版本,与你试图尽可能多地做到这一点,以显示你特别错误的地方.这是评论:

raw = 'asdfaa3fa'
lst = [str.isalnum, str.isalpha, str.isdigit, str.islower, str.isupper]   # notice youre treating the functions just like variables and aren't actually calling them. That is, you're writing str.isalpha instead of str.isalpha()
for f in range(0,5):
    counter = 0
    for i in xrange(len(raw)):
        if lst[f](raw[i]) == True:  # In your attempt, you were checking if lst[f]==True; lst[f] is a function so you are checking if a function == True. Instead, you need to pass an argument to lst[f](), in this case the ith character of raw, and check whether what that function evaluates to is true
            print lst[f] 
            counter = 1
            print True
            break
    if counter == 0:
        print False
Run Code Online (Sandbox Code Playgroud)