Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.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 将列表传递给函数_Python_Loops - Fatal编程技术网

Python 将列表传递给函数

Python 将列表传递给函数,python,loops,Python,Loops,我需要执行一个包含两个整数的列表的计算。我也在使用for循环。我不知道在计算过程中我该如何更改列表。我已经尝试了下面的代码。有人能帮我找到更好的方法吗 def calculation(input1,input2): for i in range(2): val = input1 cal1 = val[0] + 5 cal2 = val[2] + 0.05 print cal1,cal2 i = i+1 #now trying to as

我需要执行一个包含两个整数的列表的计算。我也在使用for循环。我不知道在计算过程中我该如何更改列表。我已经尝试了下面的代码。有人能帮我找到更好的方法吗

def calculation(input1,input2):
    for i in range(2):
    val = input1

    cal1 = val[0] + 5
    cal2 = val[2] + 0.05
    print cal1,cal2

    i = i+1
    #now trying to assign 'input2' to 'val'
    input1 = "input"+str(i)




input1 = [10,20,30,40]
input2 = [1,2,3,4]  
calculation(input1,input2)

my output results should look like
>> 15,20.5
>>6,2.5

你让事情变得比你需要的困难多了。只需迭代输入列表:

def calculation(input1,input2):
    for val in (input1, input2):
      cal1 = val[0] + 5
      cal2 = val[2] + 0.05
      print cal1,cal2
或者更简单一点:

def calculation(*inputs):
    for val in inputs:
        ...

传递列表,然后在该列表上执行for循环:

def calculation(ls):
    for list in ls:
        #your code here, list is input 1 and then input 2

另外,您添加了0.05而不是0.5,并且索引错误,它应该是val[1]而不是val[2](在我的代码中:list[1])

以下是一个适用于python2和python3的解决方案:

def calculation(input_lists, n):
    for i in range(n):
        val = input_lists[i]
        cal1 = val[0] + 5
        cal2 = val[2] + 0.05
        print (cal1,cal2)

input1 = [10,20,30,40]
input2 = [1,2,3,4]  
calculation([input1,input2], 2)

这将适用于任何数量的输入(包括零,您可能需要也可能不需要)。本例中的
*
运算符将所有参数收集到一个列表中,可以对该列表进行迭代,并在每个成员上运行计算

def calculation(*inputs):
    for val in inputs:

        cal1 = val[0] + 5
        cal2 = val[2] + 0.05
        yield cal1, cal2


input1 = [10,20,30,40]
input2 = [1,2,3,4]

for c in calculation(input1,input2):
    print(c)
我还修改了您的函数,以便为每次迭代生成答案,因此调用方可以决定如何处理它。在这种情况下,它只是打印它,但它可以在进一步的计算中使用它

结果是

(15, 30.05)
(6, 3.05)

这与您需要的结果不同,但基于您在原始代码中使用的索引,它是正确的。您应该再次检查您的计算。

input1=“input”+str(i)
只会在变量input1中设置字符串“input2”。是的,我理解。如何进一步将字符串转换为列表?您甚至不使用
input2
变量,为什么要使用它?很高兴能帮助您,当
input\u列表
变量知道它的长度时,为什么还要使用
n
变量?如果更改
输入列表的长度,而不是
n
,则可能会出错。这很像
c
,但至少在那里是合理的。