-2

这运行正常:

x={'1':100,'2':200,'3':300}
print("I scored %(1)s"%x)

这不会:

x={1:100,2:200,3:300}
print("I scored %(1)s"%x)

如何修改 print() 语句,以便它使用整数键 1 访问 dict 项?

4

1 回答 1

4

%(name)x格式始终使用字符串在字典中查找名称。

请改用较新的str.format()方法

>>> x={1:100,2:200,3:300}
>>> "I scored {0[1]}".format(x)
'I scored 100'
于 2013-10-28T08:34:43.777 回答