【问题标题】:Why does this function not work for this specific instance为什么此功能不适用于此特定实例
【发布时间】:2022-01-05 20:06:26
【问题描述】:

所以我创建了这个带有两个参数的函数(一个带有一个参数和一个列表的函数)。它的目的是遍历列表并在函数的每个实例都为真时返回真(否则返回假)。所以对于我的尝试,我有这个:

def all_iter(func, ls):
    i = 0
    c = True    
    for i in ls:
     if func(ls[i]) == False:
        c = False
        break
    return c   

现在这些是我用来查看它是否正常运行并且应该返回的三个示例:

>>>all_iter(lambda x: x >= 0, [1, 2, 3, 0, 4])
True
>>> all_iter(lambda x: x >= 0, [1, 2, -3, 0, 4])
False
>>> all_iter(lambda x: x % 2 == 0, [100, 10, 2022, 12])
True

现在对于前两个示例,我在运行时得到的结果是正确的,但对于第三个示例,我得到: 在 all_iter 中 如果 func(ls[i]) == 假: IndexError: 列表索引超出范围。有人可以提供一些帮助吗?

【问题讨论】:

  • for 循环遍历 ,而不是索引。巧合的是,前两个列表中的每个值也是列表中的有效索引。在前两种情况下,您得到了预期的答案,但您的函数没有工作if not func(i):
  • 你为什么要ls[i]
  • 考虑改用for i in range(len(ls)): 吗?要么这样,要么只是做func(i)而不是func(ls[i])
  • 这里没有理由考虑range(len(ls));索引不感兴趣。
  • @juanpa.arrivillaga 遍历列表的值

标签: python function loops


【解决方案1】:

这个循环:

    for i in ls:
     if func(ls[i]) == False:

仅当ls 的每个元素i 也是ls 的有效索引时才有效。在您的前几个输入中,所有元素碰巧都小于列表的长度,但您在最后一种情况下点击了IndexError,因为值要大得多。

你可能打算做的是:

   for i in ls:
       if not func(i):

请注意,有一个内置函数 all 可以简化整个事情:

def all_iter(func, ls):
    return all(func(i) for i in ls)

或等同于map():

def all_iter(func, ls):
    return all(map(func, ls))

【讨论】:

    【解决方案2】:

    替换

    for i in ls:
    

    通过

    for i in range(len(ls)):
    

    【讨论】:

      【解决方案3】:

      如果您对更多的 Pythonic 解决方案不满意,您可以以这种方式遍历索引,同时保持函数的相对样式相同:

      def all_iter(func, ls):
          c = True
          for i in ls:
           if func(i) == False:
              c = False
              break
          return c
      
      print(all_iter(lambda x: x >= 0, [1, 2, -3, 0, 4]))
      print(all_iter(lambda x: x % 2 == 0, [100, 10, 2022, 12]))
      

      分别返回 False 和 True。如果您希望将值返回为 all() 的闭包,那么它将是这样的:

      def all_iter(func, ls):
          return all(func(i) for i in ls)
      

      all 闭包将为内联 lambda 中的每个值执行函数,它基本上在一行中完成所有函数,并且仅当每个元素都与传入的函数一起工作时才返回一个布尔值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 2011-09-20
        • 2015-07-18
        • 2019-11-01
        相关资源
        最近更新 更多