Python 字典值在打印时不会显示在后面的代码部分中
忽略所有这些化学需氧量,除了我指出的斑点,我会说#######看看这些斑点:Python 字典值在打印时不会显示在后面的代码部分中,python,dictionary,Python,Dictionary,忽略所有这些化学需氧量,除了我指出的斑点,我会说#######看看这些斑点: ans = raw_input('Enter Amount of Players: ').lower() if ans == '2': a = raw_input('What is Player 1 named: ') b = raw_input('What is Player 2 named: ') cf={a:{}, b:{}} cf[a] = a cf[b] = b
ans = raw_input('Enter Amount of Players: ').lower()
if ans == '2':
a = raw_input('What is Player 1 named: ')
b = raw_input('What is Player 2 named: ')
cf={a:{}, b:{}}
cf[a] = a
cf[b] = b
p1 = raw_input(a + ", what is your city named: ")
p2 = raw_input(b + ", what is your city named: ")
cf={a:{p1:50}, b:{p2:50}}
##Look here, print cf ##
print cf
for key, cf in cf.items():
print(key)
for attribute, value in cf.items():
print('{} : {}'.format(attribute, value))
answer = raw_input ("Hit 'Enter' to continue")
def cva(x):
y = cf[ques][city]
y = float(y)
return x + y
while True:
one = raw_input("Type 'view' to view civil form, type 'change' to change civil order, or 'add' to add a city: ")
if one == 'change':
ques = raw_input('Enter Name of Player That Will Change His/Her Civil Form: ').lower()
city = raw_input(ques + ' Enter Name Of City That Will Change Civil Form: ').lower()
inc = raw_input(ques + ' Enter Amount of change for ' + city + ": ").lower()
##Look here, print cf##
print cf
cf[ques][city]=cva(float(inc))
for key, cf in cf.items():
print(key)
for attribute, value in cf.items():
print('{} : {}'.format(attribute, value))
elif one == 'view':
for key, cf in cf.items():
print(key)
for attribute, value in cf.items():
print('{} : {}'.format(attribute, value))
elif one == 'add':
ch1 = raw_input('Enter the Name of Player That Will Add a City: ')
ch2 = raw_input(ch1 + ', Enter The Name of Your New City: ')
cf[ch1][ch2] = '50'
elif one == 'over': break
elif one == 'game over': break
elif one == 'quit': break
我告诉过你要看的代码的两部分基本上是打印字典。当我输入名称“Andrew”和“Matt”以及城市“Po”和“Lo”时,第一个打印结果如下:{Matt':{'Lo':50},'Andrew':{'Po':50}
马特的第二张照片是这样的:{'Po':50}
安德鲁的第二张照片是这样的:{'Lo':50}
为什么玩家的名字在第二次打印时没有像第一次打印时那样出现。是因为名字被删除了吗?如果是,您能告诉我如何解决此问题吗?问题在于您的循环
for key, cf in cf.items():
for attribute, value in cf.items():
print('{} : {}'.format(attribute, value))
由于将其中一个迭代变量命名为与正在迭代的字典相同的名称,因此会出现问题。
cf
将在此循环之后包含最后一项的值
将迭代变量cf
重命名为其他变量,如
for key, dict_val in cf.items():
for attribute, value in dict_val.items():
print('{} : {}'.format(attribute, value))
事情应该会好起来。既然代码中只有一部分是相关的,你能把它进一步简化为必要的部分吗?如果您可以对
raw_输入
提示的答案进行硬编码,这样我们就可以运行程序并查看结果,而无需键入任何内容,这将非常有用。请参阅以获取指导。