Python如何无需逐个调用.append()将不同数据追加至对应列表
实现方案
完全可以不用逐一对每个列表调用.append()完成数据批量添加,最简洁的实现方式是先结构化收集单条全量字段,再通过zip解包一次性拆分到对应列表。
优化代码
版本1:仅保留单次append
from datetime import datetime, date def collect_title_bbc(URL): soup = get_html(URL) news_collection = [] other_tags=soup.find_all('li',{'class':'media-list__item media-list__item--1'}, limit=3) for tag in other_tags: media_block = tag.find('div',{'class':'media__content'}) title = media_block.find('h3').get_text().strip('\n ') link = media_block.find('a').attrs['href'] first_paragraph = media_block.find('p').get_text().strip('\n ') crawl_time = create_time() # 单条数据打包为元组,仅需一次append news_collection.append( (title, link, first_paragraph, crawl_time) ) # 一次性拆分填充四个目标列表 titles, links, first_paragraphs, times = map(list, zip(*news_collection)) # 补充返回值,调用时可直接获取四个结果列表 return titles, links, first_paragraphs, times def create_time(): dattime=datetime.now() tim=dattime.strftime('%H : %M : %S') dat=date.today() real_date=dat.strftime('%B %d %Y') time='Date: '+real_date+' Time: '+tim return time
版本2:完全无显式append
如果希望彻底不写.append(),可以直接用列表推导式生成全量数据集,再做拆分:
from datetime import datetime, date def collect_title_bbc(URL): soup = get_html(URL) other_tags=soup.find_all('li',{'class':'media-list__item media-list__item--1'}, limit=3) # 列表推导直接生成所有新闻条目,无显式append调用 news_collection = [ ( tag.find('div',{'class':'media__content'}).find('h3').get_text().strip('\n '), tag.find('div',{'class':'media__content'}).find('a').attrs['href'], tag.find('div',{'class':'media__content'}).find('p').get_text().strip('\n '), create_time() ) for tag in other_tags ] titles, links, first_paragraphs, times = map(list, zip(*news_collection)) return titles, links, first_paragraphs, times def create_time(): dattime=datetime.now() tim=dattime.strftime('%H : %M : %S') dat=date.today() real_date=dat.strftime('%B %d %Y') time='Date: '+real_date+' Time: '+tim return time
原理说明
- 核心用Python内置的
zip(*可迭代对象)解包语法:传入存了所有新闻元组的列表后,zip会自动把所有元组相同位置的元素聚合为一组,刚好对应标题、链接、首段、时间四个分组 - 外层套
map(list, ...)是因为zip默认返回元组类型,转成list后和你原有代码的列表类型保持一致 - 这种写法后续如果要新增/删除采集字段,只需要调整元组内的字段顺序和最终赋值的变量数量即可,不用反复增删append语句,维护成本更低
注意:原代码没有写return语句,执行完函数拿不到填充好的列表,优化版本补充了返回逻辑,调用函数时可以直接用四个变量接收结果。
内容的提问来源于stack exchange,提问作者Sua
相关产品推荐
相关产品推荐

