我在Python的edx在线课程,我必须做这个小程序,我认为该函数是正确的,但它有错误时,一个元素从列表中删除突然下一个元素不考虑进入测试。python函数的奇怪行为
def f(i):
return i + 2
def g(i):
return i > 5
def applyF_filterG(L, f, g):
"""
Assumes L is a list of integers
Assume functions f and g are defined for you.
f takes in an integer, applies a function, returns another integer
g takes in an integer, applies a Boolean function,
returns either True or False
Mutates L such that, for each element i originally in L, L contains
i if g(f(i)) returns True, and no other elements
Returns the largest element in the mutated L or -1 if the list is empty
"""
# Your code here
i = 0
if len(L) == 0:
return -1
while i < len(L):
if not g(f(L[i])):
del L[i]
i += 1
return max(L)
如果我尝试这个例子L = [0,-10,5,6,-4,-2],L的值应为L = [5,6],但其结果是这[-10,5,6,-2]当0被删除时,元素-10被跳过,-4和-2发生同样的情况。请帮忙,我不知道如何解决这个问题。
长话短说:你永远不想在迭代它的同时改变列表。 – elethan
如果您确实想要在列表中迭代时删除元素(即使这通常不是一个好主意),但最好的方法是从最大的索引开始,向最小的方向工作。这样当一个元素被删除时,它的删除不会改变你仍然需要访问的元素的任何索引。 –