python - 我需要创建一个列表,其中包含一次取三个列表的所有总和,即添加前 3 个元素,然后添加下 3 个

标签 python list python-3.x

<分区>

我需要添加列表的前三个元素,然后添加列表的后三个元素,依此类推。这是我到目前为止得到的代码:

def get_triple_sums_list(a_list):
    new_list = []
    for numbers in range(0,len(a_list)):
        numbers = sum(a_list[:3])
        new_list.append(numbers)
        return new_list
    if a_list == []:
        return []

对于列表:

 [1, 5, 3, 4, 5, 2]

这反过来又给了我结果:

[9]

我需要得到

[9, 11]

如果剩余的数字小于 3,它会给出总和的余数,即,

[1, 6, 2, 4, 3]

给我

[9, 7]

[1, 6, 2, 4]

给我

[9, 4]

最佳答案

让我们分析一下您的代码!

def get_triple_sums_list(a_list):
    new_list = []
    for numbers in range(0,len(a_list)):
        numbers = sum(a_list[:3]) #You should be using the variable
                                  #numbers here somehow.
       #^^^^^^^ - You are overwriting the for-loop index.
        new_list.append(numbers)
        return new_list  #Why are you returning here? You should be
                         #appending to `new_list`.
    if a_list == []:
        return []

固定代码如下:

def get_triple_sums_list(a_list):
    new_list = []
    for index in range(0,len(a_list), 3): #Range takes a 3rd param!
        total = sum(a_list[index:index+3])#Get all the elements from the
                                          #index to index+3
        new_list.append(total)
    return new_list

更新:似乎正在进行缩短比赛 - 我不想落在后面。这是我想添加到列表中的丑陋版本。

>>> a = [1,2,3,4,5,6,7,8]
>>> a += [0]*(len(a)%3) #For people who are too lazy to import izip_longest
>>> map(sum,zip(a[::3], a[1::3], a[2::3]))
[6, 15, 15]

关于python - 我需要创建一个列表,其中包含一次取三个列表的所有总和,即添加前 3 个元素,然后添加下 3 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39828260/

相关文章:

python - 如何使用pygame使圆形物体跳跃?

python - 我如何从 SELECT 查询中获取最大值或最小值

python - 以dict形式访问类属性 python django

python - 如何从这个字典列表中找到具有玩家 ID 的 5 个最大分数?

带有列表参数的 Python sum() 函数

python-3.x - 当最大像素值小于65535时,如何规范化uint16图像并将其转换为uint8?

c# - 通过开始和结束索引获取 List<Item> 的一部分

c# - 将多个值更新为 c# 中的对象列表

python - python 中的拼字游戏

Python Maria DB 语法