猿问

使用 find() 方法时出现 AttributeError

希望有人能解释一下这个...


我是 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 retval


def 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)

`


结果:

郎朗坤
浏览 798回答 1
1回答

千万里不及你

list对象没有find方法。这两个str和list对象都有一个index方法,但只能str有find方法。对于字符串,这两种方法基本相似,只是当字符串中不存在参数时,index将抛出异常并find返回-1。
随时随地看视频慕课网APP

相关分类

Python
我要回答