python - 解释器在尝试进行列表理解时说缩进/空格使用不一致
问题描述
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 []
解决方案
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]
推荐阅读
- api - 如何在 Twitter 上搜索特定的表情符号(Twitter Premium API)?
- python - 如何在python中获取轴坐标
- powershell - 在 powershell 中删除关闭按钮 $host.ui.PromptForCredential
- linux - 没有包管理器时如何安装软件
- java - 您的 SQL 语法中存在错误,以便在“join-date DATE,credit DOUBLE(15,0) zerofill,PRIMARY KEY(id))”附近使用正确的语法
- python - Python numpy'数组索引太多'
- python - 如何在 tkinter 上制作秒表/计时器
- flutter - 在 Flutter 中映射流
- python - pygame窗口上奇怪的黑色矩形
- flutter - Flutter:如何将数字存储为 String Sqflite?