类型错误:'int' 对象不可迭代,在 for 循环中

时间:2021-03-23 16:56:16

标签: python-3.x string for-loop

我的 for 循环不断出现同样的错误(TypeError: 'int' object is not iterable ),我不知道我的错误是什么。任何帮助将不胜感激!

import random

def compte(l,v):
    nbreOccurences = 0
    for i in l:
        if (i == v):
            nbreOccurences = nbreOccurences + 1
    return nbreOccurences

N = 100
            
l3 = []
for i in range(N):
    v = random.randrange(1,N+1)
    l3.append(v)

print(l3)
print(compte(13,3))            

2 个答案:

答案 0 :(得分:1)

L 是一个数字,而不是一个列表。 也许你的意思是:

import random

def compte(l,v):
    nbreOccurences = 0
    for i in l:
        if (i == v):
            nbreOccurences = nbreOccurences + 1
    return nbreOccurences

N = 100
        
l3 = []
for i in range(N):
    v = random.randrange(1,N+1)
    l3.append(v)

print(l3)
print(compte(range(13),3))
#### Here    ^^ 

编辑: 如果您想要这样的列表,我的回答才是正确的

[0,1,2,3,4,5,6,7,8,9,10,11,12]

在这种情况下,看起来@Shuvam Paul(下)是正确的。 这表明使用有意义的名称命名变量是多么重要。

答案 1 :(得分:0)

我猜程序的问题是打字错误。在最后一行,而不是

print(compte(13,3)) 

我猜会是,

print(compte(l3,3)) 

在 python 中,for 循环只遍历一个序列,如列表、范围、元组等。这就是发生这个问题的原因。

因此代码将作为

import random
def compte(l,v):
    nbreOccurences = 0
    for i in l:
        if (i == v):
            nbreOccurences = nbreOccurences + 1
    return nbreOccurences

N = 100
            
l3 = []
for i in range(N):
    v = random.randrange(1,N+1)
    l3.append(v)

print(l3)
print(compte(l3,3))

谢谢。