【发布时间】:2016-06-26 11:35:30
【问题描述】:
首先要理解收缩(在结尾段落中),您需要用鹰眼仔细观察这四个场景:
(如果发现任何愚蠢的错误,请忽略,了解问题所在)
第一个:
r={'A':'aa','B':'bb','C':'cc'}
print(r[A])#this gives error as "A" in not inside Quotation marks
第二个:
r={'A':'aa','B':'bb','C':'cc'}
print(r['A']) #now there is no error in output result
第三:
r={'A':'aa','B':'bb','C':'cc'}
for xyz in r:
print(r[A]) # again there will be error in output result
# because "A" is not inside quotation marks.
第四:
r={'A':'aa','B':'bb','C':'cc'}
for xyz in r:
print(r['A']) #not no error will be there as "A" is inside
#quotation marks
矛盾从这里开始循环
第 5 次:
r={'A':'aa','B':'bb','C':'cc'}
for xyz in r:
print(xyz) #output result come as A C B with no quotation
mark, you can check to see
第六:
r={'A':'aa','B':'bb','C':'cc'}
for xyz in r:
print(r[A]) # shows error in output as "A" is not inside
# quotation marks
第 7 次:
r={'A':'aa','B':'bb','C':'cc'}
for xyz in r:
print(r['A']) #result comes out successfully as aa aa aa with new
line inbetween
8:
r={'A':'aa','B':'bb','C':'cc'}
for xyz in r:
print(r['xyz']) #result should come successfully as r['xyz'] means
r['A'] or r['B'] or r['C'] in the loop
#but it shows error which by omitting the quotation
mark of xyz show the result successful as shown in
9th scenario
9:
r={'A':'aa','B':'bb','C':'cc'}
for xyz in r:
print(r[xyz]) #output result comes successfully as aa cc bb
(check to see)
矛盾:在第 9 种情况下,字面上的 print(r[xyz]) 在 xyz 周围没有引号意味着 print(r[A]) 或 print(r[B]) 或 print(r[C]) 显示成功的输出结果,并且在第 8 种情况下 print(r['xyz']) 在其输出结果中显示错误。 现在这与以下内容相矛盾:
print(r[A]) 显示的第 1 种场景、第 3 种场景和第 6 种场景
错误,因为“A”不在引号内...第二个场景,第4个场景和第7个场景,把“A”放在里面
引号成功给出结果。
现在我的问题是引号还是不带引号??它有一个通用规则还是多个规则??
【问题讨论】:
-
您混淆了字符串和变量。
r中的键是字符串。您可以将这些字符串放在一个变量中,并使用该变量来查找相应的值。 -
这里没有矛盾,只是对什么是变量,什么是字符串值的误解。引号构成一个字符串值。
标签: python dictionary key