我需要添加列表的前三个元素,然后添加列表的后三个元素,依此类推。这是我到目前为止得到的代码:
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]