【问题标题】:Python update list elements one at a time until sum(list) is reachedPython 一次更新一个列表元素,直到达到 sum(list)
【发布时间】:2019-03-03 16:37:22
【问题描述】:

我有一个以全零开头的列表。我想对列表中的每个元素连续添加一个整数,直到整个列表的总和达到某个点。

假设我希望列表总和等于 24。当我尝试时,它几乎使它看起来有效:

myList = [0,0,0,0,0,0]

while sum(myList) < 24:
    myList =  [x+1 for x in myList]

这让我得到 myList = [4,4,4,4,4,4],但如果我希望总数不能被列表中的元素数整除,则会中断。

我不知道如何将一个添加到第一个元素,然后是第二个,依此类推,然后从头开始,直到达到总和。

所以,我想要

myList = [0,0,0,0,0,0]

while sum(myList) != 22:
    myList =  <method here>

返回

myList = [4,4,4,4,3,3]

感谢您的指导。

【问题讨论】:

    标签: python


    【解决方案1】:

    你需要保留一个索引,当你到达终点时循环到前面:

    i = 0
    while sum(myList) != 22:
        myList[i] += 1
        i = (i + 1) % len(myList)
    

    (i + 1) % len(myList) 表达式将索引循环回 0,否则您会将 i 递增到超出范围。

    演示:

    >>> myList = [0, 0, 0, 0, 0, 0]
    >>> i = 0
    >>> while sum(myList) != 22:
    ...     myList[i] += 1
    ...     i = (i + 1) % len(myList)
    ...
    >>> myList
    [4, 4, 4, 4, 3, 3]
    

    知道有could just calculate the values,但是没有一次递增一个值:

    def distribute(oranges, plates):
        base, extra = divmod(oranges, plates)
        return [base + (i < extra) for i in range(plates)]
    

    对于您的示例,有 6 个插槽和 22 个项目,给出:

    >>> distribute(22, 6)
    [4, 4, 4, 4, 3, 3]
    

    【讨论】:

      【解决方案2】:

      你甚至不需要循环,你可以直接构建列表:

      target = 22
      length = 6
      
      quotient, remainder = divmod(target, length)
      
      out = [quotient+1] * remainder + [quotient] * (length-remainder)
      
      print(out, sum(out))
      # [4, 4, 4, 4, 3, 3] 22
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-19
        • 2014-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-25
        • 2014-09-10
        相关资源
        最近更新 更多