Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在序列中接受>1个位置参数_Python_Python 3.x - Fatal编程技术网

Python 如何在序列中接受>1个位置参数

Python 如何在序列中接受>1个位置参数,python,python-3.x,Python,Python 3.x,这是我的密码: def max_sum2(nums): new_sequence = [] # first run: add up positive numbers for i in range(0, len(nums)): if i >= len(nums) - 1: if nums[i - 1] >= 0 and nums[i] >= 0: new_sequence.append

这是我的密码:

def max_sum2(nums):
    new_sequence = []
    # first run: add up positive numbers
    for i in range(0, len(nums)):
        if i >= len(nums) - 1:
            if nums[i - 1] >= 0 and nums[i] >= 0:
                new_sequence.append(nums[i - 1] + nums[i])
            else:
                new_sequence.append(nums[i - 1])
                new_sequence.append(nums[i])
        if nums[i] >= 0 and nums[i + 1] >= 0:
            new_sequence.append(nums[i] + nums[i + 1])
        else:
            new_sequence.append(nums[i])
            new_sequence.append(nums[i + 1])
    return new_sequence
当我试着

printmax_sum23、-10、4、-1、2、3、6、-7

它给出了以下错误:

Traceback (most recent call last):
File "D:/Coding/Daniel/CS2231/Test.py", line 36, in <module>
    print(max_sum2(3, -10, 4, -1, 2, 3, 6, -7))
        TypeError: max_sum2() takes 1 positional argument but 8 were given
我可以问一下如何使用这些序列作为num,num。。。有效地,或者如何接受多个参数


注意:代码未完成,请不要突出显示未完成区域

正如错误消息所示,您定义了一个接受单个参数的函数,并尝试将其中八个参数传递给它。两个最简单的修复方法是:

使用单个iterable作为参数调用它: 重新定义函数以接受任意数量的参数:
为此,可以在python中使用“*”

例:


把它们放在一个列表中?就像在中一样,试着一个接一个地挑出序列并附加到一个列表中?谢谢!我漏掉了那部分,我用了你的方法1。 print(max_sum2((3, -10, 4, -1, 2, 3, 6, -7))) def max_sum2(*nums):
def max_sum2(*nums):