在我正在做的家庭作业中,我遇到了以下问题,我无法在 Python-3 函数中回答这个问题:
"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 并遇到了这个问题。我想它涉及以下的一些组合:
拆分列表,
if [i] % 2 == 0:
然后连接交替的加号和减号。
最佳答案
def alternate(l):
return sum(l[::2]) - sum(l[1::2])
取所有偶数索引元素的总和并减去所有奇数索引元素的总和。空列表总和为 0
,因此它巧合地处理长度为 0 或 1 的列表,而没有专门针对这些情况的代码。
引用资料:
关于python - 编写一个在列表索引之间交替加号和减号的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41339744/