【问题标题】:Sum a list of numbers until a number X is found对数字列表求和,直到找到数字 X
【发布时间】:2015-10-11 16:59:39
【问题描述】:

在我的程序中,我需要放置一个 while 函数,该函数将这个列表求和,直到找到一个特定的数字:

[5,8,1,999,7,5]

输出应该是 14,因为它和 5+8+1 相加并在找到 999 时停止。

我的想法是这样的:

def mentre(llista):
  while llista != 999:
    solution = sum(llista)
return solution

【问题讨论】:

  • 你查看过sum的文档吗?和while循环?您正在将 list (llista) 与 int (999) 进行比较。

标签: python list python-2.7 sum


【解决方案1】:

使用iter-函数:

>>> l = [5,8,1,999,7,5]
>>> sum(iter(iter(l).next, 999))
14

iter 调用第一个参数,直到找到第二个参数。所以把所有的数字相加,直到找到 999。

【讨论】:

    【解决方案2】:

    由于您提到使用while 循环,您可以尝试使用itertools.takewhile 的基于生成器的方法:

    >>> from itertools import takewhile
    >>> l = [5,8,1,999,7,5]
    >>> sum(takewhile(lambda a: a != 999, l))
    14
    

    只要谓词 (a != 999) 为真,生成器就会从列表 l 中消费,并将这些值相加。谓词可以是您喜欢的任何内容(如普通的while 循环),例如您可以在值小于 500 时对列表求和。

    【讨论】:

      【解决方案3】:

      一个显式使用while循环的例子如下:

      def sum_until_found(lst, num):
          index = 0
          res = 0
          if num in lst:
              while index < lst.index(num):
                  res += lst[index]
                  index += 1
          else:
              return "The number is not in the list!"
          return res
      

      另一种可能的方式是:

      def sum_until_found(lst, num):
          index = 0
          res = 0
          found = False
          if num in lst:
              while not found:
                  res += lst[index]
                  index += 1
                  if lst[index] == num:
                      found = True
          else:
              return "The number is not in the list!"
          return res
      

      有很多方法可以在不使用 while 循环的情况下做到这一点,其中一种是使用递归:

      def sum_until_found_3(lst, num, res=0):
          if num in lst:
              if lst[0] == num:
                  return res
              else:
                  return sum_until_found_3(lst[1:], num, res + lst[0])
          else:
              return "The number is not in the list!"
      

      最后,一个更简单的解决方案:

      def sum_until_found(lst, num):
          if num in lst:
              return sum(lst[:lst.index(num)])
          else:
              return "The number is not in the list!"
      

      【讨论】:

        【解决方案4】:

        使用index 并切片

        def mentre(llista):
            solution = sum(lista[:lista.index(999)])
            return solution
        

        演示

        >>> lista =  [5,8,1,999,7,5] 
        >>> sum(lista[:lista.index(999)])
        14
        

        【讨论】:

        • 有趣!但我认为它不如带有哨兵值或临时性的 iter 有效。我认为这些选项会扫描列表一次,而此选项会扫描列表两次。 (虽然我没有运行测试)
        • 是的。它们更好,因为这是 O(n2)。 :)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-30
        • 1970-01-01
        • 2023-02-15
        • 1970-01-01
        • 2016-09-19
        • 1970-01-01
        相关资源
        最近更新 更多