我创建了2个空列表,并希望将它们组合在一个字典中。但是,当我打印它时,它显示一个空字典。输出也如下所示。
def game():
empt_list=[]
empt_list_meaning=[]
empt_dict = dict(zip(empt_list, empt_list_meaning))
a_options = input("Please select one of these options: ")
if a_options == 1:
a_newword = raw_input("What word you want to add? ")
empt_list.append(a_newword)
a_newword_meaning=raw_input("add the meaning of the word: ")
empt_list_meaning.append(a_newword_meaning)
elif a_options==2:
print(empt_dict)
print ("would you like to continue or exit?\n1.contine\n2.exit")
now = input(">>> ")
if now == 1:
game()
else:
print "bye"
game()
这是输出:
Please select one of these options: 1
What word you want to add? umer
add the meaning of the word: name
would you like to continue or exit?
1.contine
2.exit
>>> 1
Please select one of these options: 1
What word you want to add? qwe
add the meaning of the word: asd
would you like to continue or exit?
1.contine
2.exit
>>> 1
Please select one of these options: 2
{}
would you like to continue or exit?
1.contine
2.exit
>>>
答案 0 :(得分:0)
您在程序中以递归方式运行game()
,这意味着每当有人输入“1”(表示继续)时,就会运行game()
。
在game()
中,首先运行的是清空列表empt_list
和empt_list_meaning
。
empt_list=[]
empt_list_meaning=[]
但是,每当有人输入1时,字典就会被清空。
一种修复方法,即制作empt_list
和empt_list_meaning
个全局变量:
empt_list=[]
empt_list_meaning=[]
def game():
global empt_list, empt_list_meaning
empt_dict = dict(zip(empt_list, empt_list_meaning))
a_options = input("Please select one of these options: ")
if a_options == 1:
a_newword = str(raw_input("What word you want to add? "))
empt_list.append(a_newword)
a_newword_meaning=str(raw_input("add the meaning of the word: "))
empt_list_meaning.append(a_newword_meaning)
elif a_options==2:
print(empt_dict)
print ("would you like to continue or exit?\n1.contine\n2.exit")
now = input(">>> ")
if now == 1:
game()
else:
print "bye"
game()
输出:
Please select one of these options: 1
What word you want to add? sldf
add the meaning of the word: lkj
would you like to continue or exit?
1.contine
2.exit
>>> 1
Please select one of these options: 1
What word you want to add? sld
add the meaning of the word: oisdf
would you like to continue or exit?
1.contine
2.exit
>>> 1
Please select one of these options: 2
{'sld': 'oisdf', 'sldf': 'lkj'}
would you like to continue or exit?
1.contine
2.exit
>>> 2
bye