【发布时间】:2016-12-03 14:18:41
【问题描述】:
我创建了一个将列表作为参数并删除空格或数字的函数。代码如下:
def cleaner(List, filter_out=' '):
if filter_out == ' ':
for i in List:
if i == ' ':
List.remove(' ')
if filter_out == 'int':
for i in List:
if type(i) == int:
List.remove(i)
我使用这样的列表对其进行了测试:
myList = ['h' ' ', 'g', 1, 2, 3, 4, 5, 'p']
print(cleaner(myList, filter_out='int'))
我希望得到['h' ' ', 'g', 'p']
而是打印出['h ', 'g', 2, 4, 'p']
为什么它离开了1 和2?我以为它会过滤掉列表中的所有数字。
【问题讨论】:
-
首先不要使用内置类型名称作为变量或参数
-
第二件事是你在迭代时没有从列表中删除的第二件事
-
打印应该不打印
-
@Marko 我们会知道的,但我认为我写的
type(i)应该将其与内置类型int进行比较
标签: python list function types