【问题标题】:How to sum consecutive duplicates in a list?如何对列表中的连续重复项求和?
【发布时间】:2019-10-25 12:35:58
【问题描述】:

我在网上做一些练习题来申请实习,结果遇到了困难。问题是对相同的连续数字求和。

示例:[1,1,3,4,4,5] ---> [2,3,8,5]

 def sum_consecutive(s):
    p = []
    for i in range(len(s)):
        if s[i] == s[i-1]:
            p.append(s[i] + s[i-1])
            p.remove(s[i])
        elif s[i] != s[i-1]:
            p.append(s[i])
    return p

在 [1,4,4,4,0,4,3,3,1] 上运行上述代码时,它应该返回 [1,12,0,4,6,1] 而不是返回

在 sum_consecutive(s) 中

    if s[i] == s[i-1]:
             p.append(s[i] + s[i-1])
             p.remove(s[i]) #This line is the problem
    elif s[i] != s[i-1]:
             p.append(s[i])

错误:

ValueError: list.remove(x): x not in list

【问题讨论】:

  • 建议:既然是申请实习,那就学习调试代码吧。对于初学者,请阅读Eric Lippert's How to debug small programs。了解如何使用打印功能和调试器,面试成功的几率会更高。
  • itertools.groupby 应该会有所帮助。
  • i=0 你最终会比较索引0 和索引-1(这是最后一个元素),因此你会得到错误(当时p 是空的)
  • 根据您的错误,您的代码中有p.remove(s[i]-1),但它不在您发布的代码中。
  • @khelwood 抱歉,我在写这个问题时犯了一个错误,但你可以尝试运行它,你会看到这个错误。

标签: python python-3.x list


【解决方案1】:

我写了这个函数,它可能很有趣,因为它很容易理解:

def count_occ(L):
    p = []
    count = 1
    for i, j in zip(L[:-1], L[1:]):
        if i != j:
            p.append(count*i)
            count = 1
        else:
            count += 1
    p.append(count*L[-1])
    return p

【讨论】:

    【解决方案2】:
    def sum_consecutive(input_list):
    i = 0
    res = []
    while(i < len(input_list)):
        j = i
        while(j < len(input_list) and input_list[i]==input_list[j]):
            j = j + 1
    
        res.append(input_list[i]*(j-i))
        i = j
    return res
    

    【讨论】:

      【解决方案3】:

      使用变量来跟踪最后看到的值,如果相同,则将其添加到当前索引中。

      def sum_consecutive(s):
          p = s[:1]   # final list
          cur = s[0]  # keep track of last seen value
      
          for i in s[1:]:  # your exercise: replace this with `range` 
              if i == cur:
                  p[-1] += i
              else:
                  p.append(i)
                  cur = i
      
          return p
      

      sum_consecutive([1, 4, 4, 4, 0, 4, 3, 3, 1])
      # [1, 12, 0, 4, 6, 1]
      

      作为奖励,我们不要忘记标准库的存在,因此您可以使用itertools.groupby 在一行中完成此操作。

      from itertools import groupby
      [sum(g) for _, g in groupby([1, 4, 4, 4, 0, 4, 3, 3, 1])]
      # [1, 12, 0, 4, 6, 1]
      

      【讨论】:

        猜你喜欢
        • 2017-01-13
        • 2019-02-23
        • 1970-01-01
        • 2016-08-24
        • 1970-01-01
        • 2014-02-13
        • 1970-01-01
        • 2016-01-19
        相关资源
        最近更新 更多