2017-05-30 124 views
-1

我需要执行一个包含2个包含整数的列表的计算。我正在使用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 
+0

'input1 =“input”+ str(i)'只会设置一个字符串'input2'到变量input1中 –

+0

是的,我明白这一点。如何进一步将字符串转换为列表? – Abdul

+0

你甚至不使用'input2'变量,那为什么呢? –

回答

2

你让事情比你需要的更加困难。只是迭代的输入列表:

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: 
     ... 
+0

辉煌。非常感谢 – Abdul

1

通行证,然后做一个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] not val [2](在我的代码:list [1]中)

+0

非常感谢答案。 – Abdul

+0

高兴地帮助你 – IsaacDj

0

这里是为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) 
+0

为什么要用'n'变量,当'input_lists'变量知道它的长度?如果你改变'input_lists'的长度,而不是'n',你可能会出错。这非常“喜欢”,但至少在那里是有道理的。 –

0

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

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) 

这是不一样你需要的结果是相同的,但它根据您在最初的代码中使用的指标是正确的。你应该再次检查你的计算。