Python 在函数之间传递变量元组
Python passing variable tuples between functions
我在一个函数中返回多个值并在不同的函数中使用它们时遇到问题。为简单起见:
def menu1():
system=system1
choice=1
return system,choice
def menu2():
option = menu1() #this assigns the option a tuple based on the first function.
if option==system1:
print"yes"
if option==1:
print"yes"
menu2()
我如何根据从前一个函数获取的值正确地给选项一个 "system1" 或“1”的值?
您可以像索引任何其他类型的序列一样索引元组:
def menu2():
option = menu1()
if option[0]==system1:
print"yes"
if option[1]==1:
print"yes"
Python 中的序列从 0 开始索引,因此第一个元素的索引为 0,第二个元素的索引为 1,依此类推。
但是,在我看来,执行以下操作更清楚:
def menu2():
system, choice = menu1()
if system==system1:
print"yes"
if choice==1:
print"yes"
这称为元组拆包,它可用于将元组的值拆分为要分配给的多个名称。
我在一个函数中返回多个值并在不同的函数中使用它们时遇到问题。为简单起见:
def menu1():
system=system1
choice=1
return system,choice
def menu2():
option = menu1() #this assigns the option a tuple based on the first function.
if option==system1:
print"yes"
if option==1:
print"yes"
menu2()
我如何根据从前一个函数获取的值正确地给选项一个 "system1" 或“1”的值?
您可以像索引任何其他类型的序列一样索引元组:
def menu2():
option = menu1()
if option[0]==system1:
print"yes"
if option[1]==1:
print"yes"
Python 中的序列从 0 开始索引,因此第一个元素的索引为 0,第二个元素的索引为 1,依此类推。
但是,在我看来,执行以下操作更清楚:
def menu2():
system, choice = menu1()
if system==system1:
print"yes"
if choice==1:
print"yes"
这称为元组拆包,它可用于将元组的值拆分为要分配给的多个名称。