创建具有可变长度参数的函数 python
Creating a function with variable-length arguments python
我需要创建一个简单的函数来计算累积和(输入元组中的每个值都应替换为所有值的总和,包括当前值,因此 (1, 2, 3) 变为 (1 , 3, 6)) 的参数,您可以假设这些参数是按值传递的。使用可变长度参数来访问这些值和 return 作为元组的结果。
我的想法是使用for循环,但我不知道如何在可变长度参数中引用前面的项目。以下是我目前所拥有的。
def simple_tuple_func(*args):
# Compute cumulative sum of each value
print(type(args))
for idx in args:
**idx += {itm}**
simple_tuple_func(1,2,3)
我加粗的行是我不确定如何引用元组(或列表、字典或任何其他作为函数参数给出的项目)中的前一项的地方。我相信如果我那条线正确吗?
只需使用itertools.accumulate
:
def simple_tuple_func(*args):
return tuple(itertools.accumulate(args, lambda x, y: x+y))
或者循环:
def simple_tuple_func(*args):
res = []
if not args:
return res
accum, *tail = args #unpacking, accum will take first element and tail de rest elements in the args tuple
for e in tail:
res.append(accum)
accum += e
res.append(accum)
return tuple(res)
这里有 live example
您可以将累计和附加到单独的列表中进行输出,以便您可以使用索引 -1
访问前面的累计和:
def simple_tuple_func(*args):
cumulative_sums = []
for i in args:
cumulative_sums.append((cumulative_sums[-1] if cumulative_sums else 0) + i)
return tuple(cumulative_sums)
这样:
simple_tuple_func(1,2,3)
会 return:
(1, 3, 6)
我需要创建一个简单的函数来计算累积和(输入元组中的每个值都应替换为所有值的总和,包括当前值,因此 (1, 2, 3) 变为 (1 , 3, 6)) 的参数,您可以假设这些参数是按值传递的。使用可变长度参数来访问这些值和 return 作为元组的结果。
我的想法是使用for循环,但我不知道如何在可变长度参数中引用前面的项目。以下是我目前所拥有的。
def simple_tuple_func(*args):
# Compute cumulative sum of each value
print(type(args))
for idx in args:
**idx += {itm}**
simple_tuple_func(1,2,3)
我加粗的行是我不确定如何引用元组(或列表、字典或任何其他作为函数参数给出的项目)中的前一项的地方。我相信如果我那条线正确吗?
只需使用itertools.accumulate
:
def simple_tuple_func(*args):
return tuple(itertools.accumulate(args, lambda x, y: x+y))
或者循环:
def simple_tuple_func(*args):
res = []
if not args:
return res
accum, *tail = args #unpacking, accum will take first element and tail de rest elements in the args tuple
for e in tail:
res.append(accum)
accum += e
res.append(accum)
return tuple(res)
这里有 live example
您可以将累计和附加到单独的列表中进行输出,以便您可以使用索引 -1
访问前面的累计和:
def simple_tuple_func(*args):
cumulative_sums = []
for i in args:
cumulative_sums.append((cumulative_sums[-1] if cumulative_sums else 0) + i)
return tuple(cumulative_sums)
这样:
simple_tuple_func(1,2,3)
会 return:
(1, 3, 6)