我们需要创建一个函数,它接受一个非负整数和字符串列表,并返回一个包含过滤字符串的新列表 | 代码大战
例子:filter_list([1,2,'a','b']) == [1,2]
我编写了以下代码,但它没有通过所有测试(第三个在修复时会引发错误)。
def filter_list(l):
new_l = []
for i in range (len(l)):
try:
int(l[i])
new_l.append(l[i])
except ValueError:
continue
return new_l
测试:
import codewars_test as test
from solution import filter_list
@test.describe('Sample tests')
def sample_tests():
@test.it('should work for basic examples')
def basic_examples():
test.assert_equals(filter_list([1, 2, 'a', 'b']), [1, 2], 'For input [1, 2, "a", "b"]')
test.assert_equals(filter_list([1, 'a', 'b', 0, 15]), [1, 0, 15], 'Fot input [1, "a", "b", 0, 15]')
test.assert_equals(filter_list([1, 2, 'aasf', '1', '123', 123]), [1, 2, 123], 'For input [1, 2, "aasf", "1", "123", 123]')