int'对象不可迭代 - 试图学习python

时间:2014-12-19 13:26:15

标签: python list object int iterable

我正在尝试学习python,我将这段代码付诸实践。目标是读取一个列表,如果数字是奇数,另一个列表接收它:

def purify(numlist):
    imp = [] #list that receive the odd numbers
    for n in range(0,len(numlist[n])): #travel a list of numbers inputted by user 
        if n % 2 != 0: #verify if number is pair or odd
            imp = numlist[n] #assigns odd numbers to the new list
    return imp #return list of odd numbers

但我收到一个错误:

'int' object is not iterable

任何人都可以帮助我吗?提前谢谢!

2 个答案:

答案 0 :(得分:0)

如果我继续写这个功能的方式。

def purify(numlist):
    imp = [] 
    # numlist is iterable. range builtin would list all integers between 0 and the value.
    for n in numlist:  
         # As pointed out in comments, the n variable will receive each number of the list iteratively. It is NOT the length of the list. 
        if n % 2 != 0: 
            # append method will add the element to the list. if you use assignemnt (=),
            # your variable imp will become an integer.
            imp.append(n)  
    return imp

更实际的方法是

imp = filter(lambda n: n % 2 != 0, numlist)  # using a python built-in

imp = [n for n in numlist if n % 2 != 0]  # using list comprehension 

答案 1 :(得分:0)

我是这样做的:

def purify(numlist):
    imp = []
    for n in range(0,len(numlist)):
        if numlist[n] % 2 == 0:
            imp.append(numlist[n])
    return imp

它正在工作!谢谢你们!