【问题标题】:How do I perform an operation iteratively on a python list/array whithout a for loop?如何在没有 for 循环的情况下在 python 列表/数组上迭代地执行操作?
【发布时间】:2020-09-16 00:28:49
【问题描述】:

是否可以对列表的前两个元素执行以下操作,存储结果,然后对列表中的所有项目的上一个结果和列表中的下一个项目执行下一个操作,而不需要 for 循环?这里 F(x) 是一个任意定义的函数。 这是带有 for 循环的工作代码:

list   = [a,b,c,d,e,f,g,h]
result = F(a,b)

for i in range(2,len(list)):
    result = F(result,list[i])

print(result)

提前非常感谢你,最好的答案是煎饼。

【问题讨论】:

    标签: python arrays list iteration


    【解决方案1】:

    是的,这是reduction

    from functools import reduce
    
    result = reduce(F, list)
    

    reduce 将函数与列表的每个元素一起应用于累加器 (result)。但是在第一次迭代中,如果您不指定初始累加器,它将使用初始元素作为累加器。

    【讨论】:

      【解决方案2】:

      有一个 reduce 函数可以做到这一点:https://www.geeksforgeeks.org/reduce-in-python/

      # importing functools for reduce() 
      import functools 
      
      # initializing list 
      lis = [ 1 , 3, 5, 6, 2, ] 
      
      # using reduce to compute sum of list 
      print ("The sum of the list elements is : ",end="") 
      print (functools.reduce(lambda a,b : a+b,lis)) 
      

      你的例子

      import functools 
      list   = [a,b,c,d,e,f,g,h]
      def F(a,b):
        return a + b #or whatever
      
      result = functools.reduce(F, list)
      
      print(result)
      

      【讨论】:

      • 谢谢,您的回答很完美。这里有一个煎饼:+1 煎饼
      【解决方案3】:

      你可以自己写函数:

      def split_and_compute(_list):
          if len(_list) > 2:
              return myother_fun(_list[0:2]) + split_and_compute(_list[2:])
          else:
              return myother_fun(_list)
      
      def myother_fun(_list):
          return _list[0] + _list[1]
      

      注意 + 作为回报 myother_fun(_list[0:2]) + split_and_compute(_list[2:]) 应该是你拥有的任何累加器,这取决于你正在处理的数据,这也处理两个元素哈克方式,可以放一些守卫在那里

      【讨论】:

      • 在这里使用+ 是一个非常糟糕的主意。这将创建 许多 个临时列表,这将浪费空间和时间。
      • python反正没有尾递归,看不出问题
      • 我没有提到 TCO。每次使用+ 都会创建一个副本。最重要的是,每次使用切片都会创建另一个副本。 myother_fun(_list[0:2]) + split_and_compute(_list[2:]) 将创建 3 个(如果我没记错的话)_list 的副本,每次迭代
      • 这有什么问题?显然他应该使用 for 循环,reduce 可能会消失,并且不鼓励在 python 中使用它,重点是向他展示它是如何完成的,而不是一个晦涩的 reduce 函数,如果你想说这是低效的,是的,同样的方式可以告诉他使用 scala 或 haskell 来做这件事,但这不是问题。
      猜你喜欢
      • 2015-02-12
      • 2017-03-25
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 1970-01-01
      • 2013-02-16
      • 2019-01-07
      相关资源
      最近更新 更多