(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
当你从一个函数返回多个值时,它会作为一个元组返回:
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。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。