我需要创建一个列表,其中包含一次三个列表的所有总和,即添加前3
发布时间:2020-12-20 11:54:49 所属栏目:Python 来源:网络整理
导读:参见英文答案 How do you split a list into evenly sized chunks?????????????????????????????????????57个 我需要添加列表的前三个元素,然后添加列表的后三个元素,依此类推.这是我到目前为止的代码: def get_triple_sums_list(a_list): new_list = [] fo
参见英文答案 >
How do you split a list into evenly sized chunks?????????????????????????????????????57个
我需要添加列表的前三个元素,然后添加列表的后三个元素,依此类推.这是我到目前为止的代码: 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,2] 这反过来给了我结果: [9] 我需要得到 [9,11] 如果剩下的数字小于3,它给我剩余的总和,即, [1,6,2,3] 给我 [9,7] 和 [1,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,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] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |