【问题标题】:How to iterate function so that output is passed as argument iteratively until condition is met如何迭代函数,以便将输出作为参数迭代传递,直到满足条件
【发布时间】:2021-06-13 06:38:06
【问题描述】:

我制作了一个称为乘法的函数,用于将列表中的后续元素相乘。

def multiplication(numbers):
  new_list=[]
  for x in range(len(numbers)-1):
    new_list.append(numbers[x+1]*numbers[x])
  return new_list

执行以下操作。

multiplication([1,3,5,7,8])
[3, 15, 35, 56]
multiplication([3,15,35,56])
[45, 525, 1960]

我一直在尝试使用 while 循环创建一个新函数,以将先前函数的输出传递回自身,直到输出单个值。例如,上面的列表应该成为 [24310125000] 的单个值。我试过使用下面的代码。

def final_multiplication(numbers):
  new_list=[]
  while len(new_list)!=1:
    for x in range(len(numbers)-1):
      new_list.append(numbers[x+1]*numbers[x])
    if len(new_list)==1:
      return new_list 

但是,我的尝试导致崩溃。有谁知道使用 while 循环来做到这一点的任何方法?

【问题讨论】:

  • 你总是添加到new_list,所以它的长度永远不会是1。我会递归地做。
  • 你能解释一下预期的输出是[24310125000]吗?我不确定你到底想做什么。

标签: python python-3.x while-loop


【解决方案1】:

一个简单的写你想做的事情的方法是:

def mult(nums):
    while len(nums) > 1:
        nums = [n1 * n2 for n1, n2 in zip(nums, nums[1:])]
    return nums

【讨论】:

    【解决方案2】:

    我敢肯定有更可爱的方式来做这件事,不涉及无用的while 和海象:

    import itertools
    import operator
    
    
    def pairwise(iterable):
        a, b = itertools.tee(iterable)
        next(b, None)
        yield from zip(a, b)
    
    numbers = [1, 3, 5, 7, 8]
    
    while len(numbers := list(itertools.starmap(operator.mul, pairwise(numbers)))) != 1:
        pass
    
    print(numbers)
    

    输出:

    [24310125000]
    >>> 
    

    【讨论】:

      【解决方案3】:

      您可以通过以下方式获得对:

      from operator import mul
      from functools import reduce
      
      x = [1,3,5,7,8]
      
      def pairs(lst):
          i = 0
          while True:
              _slice = lst[i:i+2]
              if not len(_slice) == 2:
                  break
              yield reduce(mul, _slice)
              i += 1
      
      
      # Then a while loop to check the length
      def reducer(lst):
          while len(lst) > 1:
              lst = list(pairs(lst))
          return lst
      
      reducer(x)
      [24310125000]
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-06
        • 1970-01-01
        • 2013-12-13
        • 2020-06-16
        • 2021-11-26
        • 1970-01-01
        • 1970-01-01
        • 2011-04-28
        相关资源
        最近更新 更多