首页 > 解决方案 > 解释器在尝试进行列表理解时说缩进/空格使用不一致

问题描述

def skip_elements(elements) :
    new_list = []
    for i in elements :
        if i % 2 == 0 :
            new_list= new_list.append(i)
            i+=1
        else :
             i+=1

    return new_list

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []

标签: pythonpython-3.xlist-comprehension

解决方案


if i % 2 == 0 :
    new_list= new_list.append(i)
    i+=1
else :
     i+=1
    ^ extra space - you might want to use tabs instead of spaces when it comes to python - or any language for that matter

new_list = new_list.append(i)

.append()将返回None。将其替换为:

new_list.append(i)

最后,返回一个包含所有奇数元素的列表需要付出很多努力。你可以简单地做(感谢@chepner):

def skip_elements(elements):
    return elements[::2]

推荐阅读