开发者社区> 问答> 正文

是否有可能将保存切片数组的4个变量保存为单个变量?

(Noob)我有一个程序,它获取一个数组,根据其各自的功能对某些元素进行切片,然后arCalc对它们进行操作。从arSlice返回所有这些值似乎不可行,因为main()中的函数调用需要5个参数,而我希望在不声明全局值的情况下完成此操作。我想知道是否可以将arSlice中的变量保存为单个变量,这样我就可以只返回intcodes和result。 同样需要明确的是:从一个函数返回一个值并不意味着其他函数可以访问该返回值?我返回intcodes在getFile,但我能以某种方式访问它在arSlice?

    def getFile(open_file):

    with open(open_file, 'r') as f:
        intcodes = f.readline().split(',')
        to_int = [int(n) for n in intcodes]
        intcodes = to_int[:]
    intcodes[1] = 12
    intcodes[2] = 2

    return intcodes


    def arSlice(intcodes):

    opcode = intcodes[0::4]        
    first_input = intcodes[1::4]   
    second_input = intcodes[2::4]  
    outputs = intcodes[3::4]
    result = # put the 4 variables above into a single list or array?

    return intcodes, opcode, first_input, second_input, outputs


    def arCalc(intcodes, opcode, first_input, second_input, outputs):


    add_ = 1
    mul_ = 2
    index = 0

    while True:
        for o in opcode:
            if o == add_:
                intcodes[outputs[index]] = (intcodes[first_input[index]] + intcodes[second_input[index]])
                index += 1
            elif o == mul_:
                intcodes[outputs[index]] = (intcodes[first_input[index]] * intcodes[second_input[index]])
                index += 1
            elif o == 99:
                break
        break
    print(intcodes)

    def main():

    myFile = getFile("day2.txt")

    mySlice = arSlice(myFile)

    arCalc(myFile, mySlice)


    if __name__=="__main__":
          main()

问题来源StackOverflow 地址:/questions/59383649/is-it-possible-to-save-4-variables-that-hold-sliced-arrays-into-a-single-variabl

展开
收起
kun坤 2019-12-27 10:12:44 373 0
1 条回答
写回答
取消 提交回答
  • 当你从一个函数返回多个值时,它会作为一个元组返回:

    def x():
        return "A", "cat", 5
    
    y = x()
    

    y现在有了值("A", "cat", 5)你可以用y[0] y[1]和y[2]来访问它们。或者,当你调用函数时,你可以把它们分配给单独的变量:

    a, b, c = x()
    

    现在a的值是a, b是cat, c是5。 您还可以在将tuple传递给函数时将其作为参数展开,因此,假设变量y仍然像上面那样存在:

    def myfunc(a, b, c):
        pass
    

    如果您调用了myfunc(y),那么在函数a中将是tuple(“a”、“cat”、5),而b和c将不会得到任何值,从而导致错误。但是如果你调用myfunc(*y)那么y就会展开,a会得到a, b会得到cat, c会得到5。

    2019-12-27 10:13:07
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载