1.map函数
接收一个函数f和一个可迭代对象(列表,字典等),并通过把函数f依次作用在li每个元素上,得到一个新的list并返回
# -*-coding:utf8 -*- import requests from lxml import etree # url='https://www.dytt8.net/html/gndy/dyzz/list_23_1.html' headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36' } # response=requests.get(url,headers=headers) #在电影天堂的网页中,因为编码方式,requests库猜错了,所以response.text出现乱码 # print(response.text) # text=response.content.decode('gbk') BaseDomain='https://www.dytt8.net' def get_detail_url(url): response=requests.get(url,headers=headers) text=response.content.decode('gbk') html=etree.HTML(text) detail_urls = html.xpath('//table[@class="tbspan"]//a/@href') map(lambda url:BaseDomain+url,detail_urls) print(detail_urls) get_detail_url('https://www.dytt8.net/html/gndy/dyzz/list_23_1.html')
使用map不会改变原值,而是得到一个新的值。比如一个列表传入,得到的是一个新的list
lis ={'egon1':1,'egon2':2,'egon3':3} ret=map(lambda x: x+' SB', lis) for i in ret: print(i)
2.filter函数
过滤掉不符合条件的元素,传一个函数和一个可迭代对象,用法和map类似。
#过滤表中所有奇数 lis =[1,2,3,4,5,6,7,8,9,10] def is_odd(n): return n % 2 ==1 new_list=list(filter(is_odd,lis)) print(new_list)