希望有人能解释一下这个...我是 Python 新手,偶然发现了一项作业(通过在线课程学习):创建了卡片组并需要移除几张卡片——我想我会在卡片组 [] 中找到 .find(str),返回它的索引 (i) 和 .remove(i)。这样我就可以验证代码是如何工作的,因为我还在学习......当我使用 .find() 方法时,出现以下错误:AttributeError: 'list' object has no attribute 'find'但是索引方法没有这样的错误:这是两种方法。`def indxcard(self,fcard): ''' :return index of -1 if not found ''' retval=-1 try: retval=self.Carddeck.index(fcard) except: # value not found retval = -1 # print only for debugging print('in Indxcard', retval,fcard) return retvaldef findcard(self, fcard): ''' :return index of card -1 if not found ''' retval = self.Carddeck.find(fcard) # Causes an attribute error... print('in find card', retval, fcard) return retval...和调用代码...print(gamedeck)print('-----------')for killzerocard in Cards.Suits: # gamedeck.killcard('0'+killzerocard[1:]) # Uno deck only as 1 Zero (0) card for each of the colors try: gamedeck.findcard('0'+killzerocard) except: print('error thrown by find') gamedeck.indxcard('0'+killzerocard)print('-----------')# gamedeck.shuffle()print(gamedeck)`结果:
1 回答

千万里不及你
TA贡献1784条经验 获得超9个赞
list
对象没有find
方法。这两个str
和list
对象都有一个index
方法,但只能str
有find
方法。对于字符串,这两种方法基本相似,只是当字符串中不存在参数时,index
将抛出异常并find
返回-1
。
添加回答
举报
0/150
提交
取消