((Noob)我有一个程序,该程序接受数组并根据某些元素的个别功能对其进行切片,然后arCalc对其进行操作。从arSlice返回所有这些值似乎不可行,因为main()中的函数调用需要5个参数,而我想在不声明全局变量的情况下完成此操作。我想知道是否可以将arSlice中的变量保存到单个变量中,这样我就可以只返回整数代码和结果。
也要清楚:从一个函数返回一个值并不成功,因此其他函数可以访问该返回值吗?我正在getFile中返回intcode,但是以某种方式能够在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()
当您从一个函数返回多个值时,它将作为元组返回:
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。
当您将元组传递给函数时,您也可以将其扩展为参数,因此假设变量y仍然如上所示:
def myfunc(a, b, c):
pass
如果您调用了myfunc(y),则在函数a中将是元组(“ A”,“ cat”,5),而b和c将不会获得任何值,从而导致错误。但是,如果您调用myfunc(* y),则y会扩展,并且a将获得“ A”,b将获得“ cat”,而c将获得5。