编写一个在列表索引之间交替使用正号和负号的函数 [英] Writing a function that alternates plus and minus signs between list indices

查看:84
本文介绍了编写一个在列表索引之间交替使用正号和负号的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在处理的作业集中,我遇到了以下问题,我在使用Python-3函数时遇到问题:

In a homework set I'm working on, I've come across the following question, which I am having trouble answering in a Python-3 function:

编写备用函数:int list->需要一个列表的int 数字,并为它们添加交替符号.例如替代 [1,2,3,4] = 1-2 + 3-4 = -2."

"Write a function alternate : int list -> int that takes a list of numbers and adds them with alternating sign. For example alternate [1,2,3,4] = 1 - 2 + 3 - 4 = -2."

完全公开,该问题是在考虑标准ML的情况下编写的,但是我一直在尝试学习Python并遇到了这个问题.我在想它涉及以下方面的组合:

Full disclosure, the question was written with Standard ML in mind but I have been attempting to learn Python and came across the question. I'm imagining it involves some combination of:

拆分列表,

if [i] % 2 == 0:

,然后将交替的正负号串联起来.

and then concatenating the alternate plus and minus signs.

推荐答案

def alternate(l):
  return sum(l[::2]) - sum(l[1::2])

取所有偶数索引元素的总和,然后减去所有奇数索引元素的总和.空列表的总和为0,因此它恰好处理了长度为0或1的列表,而没有专门针对这些情况的代码.

Take the sum of all the even indexed elements and subtract the sum of all the odd indexed elements. Empty lists sum to 0 so it coincidently handles lists of length 0 or 1 without code specifically for those cases.

参考文献:

这篇关于编写一个在列表索引之间交替使用正号和负号的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆