问题描述:
In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.
Example:
filter_list([1,2,'a','b']) == [1,2]
filter_list([1,'a','b',0,15]) == [1,0,15]
filter_list([1,2,'aasf','1','123',123]) == [1,2,123]
代码实现:
#codewars第三题:
def filter_list(l):
_length = len(l)
j = 0
new_l = [] #使用列表前要先定义列表
for i in range(0,_length):
if type(l[i]) == str or l[i] < 0:
continue
else:
new_l.append(l[i]) #相当于在列表中插入值 !!!注意使用del 、 pop 、 remove 语句会使list长度变短
j += 1
return new_l
#第二中解决方法
def filter_list(l):
return [x for x in l if type(x) is not str]
#第三种方法
def filter_list(l):
return [i for i in l if not isinstance(i, str)]
filter_list([1,2,'aasf','1','123',123])