我必须为一个元素在一个列表中出现的次数做一个计数器,使用真正基本的循环和有限的操作数。 当我不使用模块并直接将其集成到代码中时,错误就消失了。在
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__'
你有}。这会导致一个错误,因为您将L视为一个列表。我相信你已经切换了}。在
L = len(a)
,然后你有{L
和{考虑重命名变量以避免混淆。单字符变量名通常不是最佳做法。在
相关问题 更多 >
编程相关推荐