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

标签 python list loops

我想看看是否可以遍历函数中的函数列表。我能找到的最接近的东西是遍历整个模块。我只想使用预先选择的函数列表。

这是我原来的问题:

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

示例输入

    qA2

示例输出(必须打印到不同的行,如果至少一个字母通过则为真,否则所有字母都未通过每次测试为假):

    True
    True
    True
    True
    True

我写这个是为了一次测试。当然,我可以只写 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

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

    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

那么我该如何修改这段代码来满足那里的所有规则呢?


使用来自所有评论的信息 - 此代码满足上述规则,并动态循环遍历每个方法。

    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)

getattr方法(我觉得这叫内省(introspection)方法?)

    raw = 'ABC'

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

列表理解方法:

    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]

最佳答案

您循环遍历函数列表的方式略有偏差。这将是一种有效的方法。您需要存储在列表中的函数是 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

示例输出:

Input                     Output
===================================
"qA2"         ----->      True True True True True
"asdfaa3fa"   ----->      True True True True

我还注意到您似乎使用索引进行迭代,这让我觉得您可能来自 C/C++ 等语言。 for in 循环结构在 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

关于python - 动态循环遍历Python函数中的函数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39422641/

相关文章:

python - 在空字典中连接元组

r - 使用 R 优化/矢量化数据库查询

ios - 如何让 UIScrollView 垂直滚动,其中包含动态数量的 subview ?

python - 使用 vtkTubeFilter 创建闭环

python - 在 Python 中执行正则表达式操作时如何保留行和列排列

python - 如何在绘图中创建非线性轴

c++ - 堆栈列表调试断言失败 C++

c++ - 如何从列表中提取某些值并将其放入另一个列表

c# - 两个不同的类中是否可以重载

python - 如何将 Python 多列表转换为列表