重复一个for循环直到完成?

时间:2015-12-11 22:32:56

标签: python list for-loop repeat

我需要创建一个函数来删除我的程序测试的任何列表中的偶数,但是,它在删除第一个偶数后停止并且我不确定如何继续它

def filter_odds(data):
     for index in range(len(data)):
        index = data[index]
        if index % 2 == 0:
            data.remove(index)
        else:
            continue
        return data
print(filter_odds([1,2,3,4,5,6]))

5 个答案:

答案 0 :(得分:3)

你有两个问题:

  1. return位于循环体内,因此在循环一次后返回
  2. 您在迭代过程中突然变异list,并且您将死于IndexError因为循环运行到list的原始长度,即使list随着你的速度缩小。
  3. 无论哪种方式,list理解都可以更好地做到这一点:

    def filter_odds(data):
        return [x for x in data if x % 2]
    

    如果由于某种原因你需要改变参数,不只是返回你关心的值的修改副本,你也可以轻松地做到这一点:

    def filter_odds(data):
        # Assigning to slice with no end points replaces contents with values
        # from new list, modifying in place
        data[:] = [x for x in data if x % 2]
        return data     # Return the mutated argument as in original code
    

    如果目标是删除偶数索引而不是偶数值,那么您可以使用扩展切片来高效且疯狂地执行此操作:

    def filter_odds(data):
        return data[1::2]
    

    或改变论点:

    def filter_odds(data):
        del data[::2]   # Deletes the even indices in place in a single pass
        return data     # Return the mutated argument as in original code
    

答案 1 :(得分:2)

使用列表理解:

odd_list = [num for num in data if num % 2 == 1]

答案 2 :(得分:2)

def filter_odds(data):
    list = []
    for index in data:
        if index % 2 != 0:
            list.append(index)
        else:
            pass
    return list

print(filter_odds([1,2,3,4,5,6])) # returns [1, 3, 5]

答案 3 :(得分:1)

你不需要else语句而且回复没有正确缩进

    def filter_odds(data):
     for number in data:           
       if number % 2 == 0:
         data.remove(number)
      # else:
      #   continue
     return data
    print(filter_odds([1,2,3,4,5,6]))

答案 4 :(得分:0)

您可以使用filter功能:

even_list = filter(lambda x: x % 2 == 0, input_list)
odd_list = filter(lambda x: x % 2 != 0, input_list)

https://docs.python.org/2/library/functions.html#filter