Discuss / Python / 能否详细说下in的语法

能否详细说下in的语法

Topic source

两段程序,list内使用整数和字符,结果不一样

第一段 d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} L = ['1','2','3'] E = ['4','5','6'] d ={L[1]:E[1]} print(d) print('%s' % L[1] in d) print('%s' % 2 in d) print('%s' % d.get(2,100)) print('%s' % 'Michael' in d)

返回结果是 {'2': '5'} TRUE TRUE 100 FALSE

符合我的预期

第二段是 d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} L = [1,2,3] E = [4,5,6] d ={L[1]:E[1]} print(d) print('%s' % L[1] in d) print('%s' % 2 in d) print('%s' % d.get(2,100)) print('%s' % 'Michael' in d)

返回结果是 {2: 5} FALSE FALSE 5 FALSE

d已经有了键值2,但是判断返回False,这个让我不解。

文中第一段 print('%s' % 2 in d) 实际写得代码是 print('%s' % '2' in d)

是复制错误

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

不要把程序搞那么复杂,把自己绕进入了:

>>> d = {2:5}
>>> 2 in d
True

廖雪峰

#4 Created at ... [Delete] [Delete and Lock User]
>>> print('%s' % 2 in d)
False
>>> print('%s' % (2 in d))
True

谢谢老师,看完我明白了,是优先级的问题

雨恋小兑

#6 Created at ... [Delete] [Delete and Lock User]
    • 把我饶了半天,终于发现是你没加括号才没按你的需求走,刚要回复你发现老师已经回复了很尴尬

你好,请问为什么会出现5和100的区别,我的理解错误点在哪里

小丑J2

#8 Created at ... [Delete] [Delete and Lock User]

请问第二段第四行为什么会返回5?

SBSquarePants

#9 Created at ... [Delete] [Delete and Lock User]
d={'2','5'}
print('%s' % 2 in d)

和

d={2,5}
print('%s' % 2 in d)

都返回ture?

SBSquarePants

#10 Created at ... [Delete] [Delete and Lock User]

使用get方法返回值的时候,把2和5当作键值对了,所以当2在(2,5)中式,返回的是5。不在则返回100。

不过这只是我的猜测。

如果是这样的话,是代码不严谨吧


  • 1
  • 2

Reply