“Int object has no attribute”从自定义modu中的append获取的列表调用list对象时出错

2024-06-16 09:41:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须为一个元素在一个列表中出现的次数做一个计数器,使用真正基本的循环和有限的操作数。 当我不使用模块并直接将其集成到代码中时,错误就消失了。在

def norepeat(a):
R=[]
i=0
while i<len(a):
    if a[i] in R:
        i=i+1
    else:
        R.append(a[i])
        i=i+1
return R

a=list(input("enter list(elements seperated by commas):"))
L=len(a)
R=norepeat(a)
print R
print R[1]
l=(len(R))
print l
i=0
while i<l:
    j=0
    count=0
    while j<L:
        if R[i]==L[j]:#error:'int' object has no attribute '__getitem__'
            count+=1
        if j==l-1:
            print R[i],"occurs",count,"times"
    j=j+1
i=i+1

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-73b7f443c37e> in <module>()
 23     count=0
 24     while j<L:
 ---> 25         if R[i]==L[j]:
 26             count+=1
 27         if j==l-1:

 TypeError: 'int' object has no attribute '__getitem__'

Tags: noininputlenifobjectcountattribute
1条回答
网友
1楼 · 发布于 2024-06-16 09:41:57

你有L = len(a),然后你有{}。这会导致一个错误,因为您将L视为一个列表。我相信你已经切换了L和{}。在

考虑重命名变量以避免混淆。单字符变量名通常不是最佳做法。在

相关问题 更多 >