filter用于对list对象的元素进行筛选操作
该过程会生成一个新的list,不会改变原list
基本用法
list(filter(function_name, list_name))
执行过程(个人理解):
将list中各元素依次传入指定function,根据function的返回值(False或True)对该元素进行取舍。最终返回一个Iterator对象。
外围list函数的作用便是迭代出Iterator的所有元素并生成一个列表。
Case
判断回数
# -*- coding: utf-8 -*-
def is_palindrome(n):
num_list = []
flag = 1
while n >= 1:
num_list.append(n%10)
n = n // 10
if len(num_list)%2 == 0:
for index, value in enumerate(num_list):
if (index+1) > len(num_list)//2:
break
if num_list[index] != num_list[-(index+1)]:
flag = 0
else:
for index, value in enumerate(num_list):
if (index+1) > (len(num_list)-1)//2:
break
if num_list[index] != num_list[-(index+1)]:
flag = 0
return flag
# 测试: output = filter(is_palindrome, range(1, 1000)) print('1~1000:', list(output)) if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: print('测试成功!') else: print('测试失败!')