希望有人能解釋一下這個...我是 Python 新手,偶然發(fā)現(xiàn)了一項作業(yè)(通過在線課程學(xué)習(xí)):創(chuàng)建了卡片組并需要移除幾張卡片——我想我會在卡片組 [] 中找到 .find(str),返回它的索引 (i) 和 .remove(i)。這樣我就可以驗證代碼是如何工作的,因為我還在學(xué)習(xí)......當我使用 .find() 方法時,出現(xiàn)以下錯誤: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...和調(diào)用代碼...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)`結(jié)果:
1 回答

千萬里不及你
TA貢獻1784條經(jīng)驗 獲得超9個贊
list
對象沒有find
方法。這兩個str
和list
對象都有一個index
方法,但只能str
有find
方法。對于字符串,這兩種方法基本相似,只是當字符串中不存在參數(shù)時,index
將拋出異常并find
返回-1
。
添加回答
舉報
0/150
提交
取消