动态地循环遍历Python中函数的函数列表 您所在的位置:网站首页 python中for循环 动态地循环遍历Python中函数的函数列表

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

2023-02-27 20:28| 来源: 网络整理| 查看: 265

1> gowrath..:

循环浏览函数列表的方式略有不同.这将是一种有效的方法.您需要存储在列表中的函数是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循环结构在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


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有