append函数_python函数中把列表(list)当参数时的"入坑"与"出坑"

本文解析了Python函数中使用列表作为默认参数时可能遇到的问题,包括列表被意外修改的情况,并提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Python函数中,传递的参数如果默认有一个为 列表(list),那么就要注意了,此处有坑.

入坑

挖坑

1153adc07dab013f7caf979e03dd99bb.png

预期结果

3bee60cbab39ada8a3344496a7cb229b.png

执行结果

295204608de6cbe65a774104d4585036.png

出坑

当定义函数时,会保存函数中默认参数 list 的值,也就是列表 li=[];

在每次调用的时候如果传递了新的列表,则使用传递的列表,没有传递,使用定义函数时保存的默认参数(li=[]);

上面两次调用中,都没有传递新的列表(使用默认列表 li=[] ),程序会调用定义函数时保存的默认参数((li=[]));

列表在append的时候会在 li=[] 原来的基础上append追加值,所以会产生以上结果.

通过打印列表的ID进行辨识

打印列表 li=[] 的ID:

2e96994ffa0c7cb25b2ef3c700892b83.png

结果:

48ed6273ec334cfb3e2a1248a2883fc3.png

会发现ID值是相同的;

说明两次执行时使用的都是定义函数时的默认参数 li=[ ]

执行时往里面传新的列表

打印列表 li=[] 的ID 和 传的新列表的ID:

487cef313af9bd44e76306d4a5743f7c.png

结果:

62318261d58bac8b84e4fd65f808cc58.png

会发现执行传递空(新)列表的函数时打印的ID不一样,而没有传递的一样;

当传递空列表时,函数体当中会使用传递的空列表,没有传递时,使用函数默认值 li=[ ], 所以会产生以上结果.

优化

如果想要达到预期的结果,只需要在函数体里进行判断即可:

4f61810c39a9c69ccafd6999d623305d.png

结果:

b34c6b82dbd4294b9dcfc9eee8e42e9a.png

转自:python函数中把列表(list)当参数时的"入坑"与"出坑"

import requests from bs4 import BeautifulSoup import os import re from urllib.parse import urljoin # 定义关键词列表 KEYWORDS = [&quot;&quot;] def sanitize_text(text): &quot;&quot;&quot;增强型文本清洗&quot;&quot;&quot; text = re.sub(r'<[^>]+>', '', text) text = re.sub(r'https?://\S+', '', text) replacements = { ' ': ' ', '&': '&', '&quot;': '&quot;', '<': '<', '>': '>' } for k, v in replacements.items(): text = text.replace(k, v) text = re.sub(r'[■◆▼©®™●【】]', '', text) text = re.sub(r'\s+', ' ', text).strip() return text def save_content(url, save_folder): &quot;&quot;&quot;安全获取并保存网页内容&quot;&quot;&quot; try: headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'} response = requests.get(url, headers=headers, timeout=10) response.encoding = 'utf-8' if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') main_content = soup.find(['article', 'div'], class_=re.compile(r'content|main')) clean_text = sanitize_text(main_content.get_text() if main_content else soup.get_text()) # 生成安全文件名 filename = re.sub(r'[\\/*?:&quot;<>|]', '', url.split('/')[-1])[:50] + '.txt' filepath = os.path.join(save_folder, filename) with open(filepath, 'w', encoding='utf-8') as f: f.write(clean_text) print(f'成功保存至: {filepath}') else: print(f'访问失败: {url} 状态码: {response.status_code}') except Exception as e: print(f'处理{url}错: {str(e)}') def main(): &quot;&quot;&quot;主程序&quot;&quot;&quot; # 设置保存路径 desktop = os.path.join(os.path.expanduser('~'), 'Desktop') folder_name = &quot;ScrapedData&quot; # 自定义文件夹名称 save_path = os.path.join(desktop, folder_name) # 创建保存目录(如果不存在) os.makedirs(save_path, exist_ok=True) # 模拟种子页面(需合法授权后替换实际目标网站) seed_url = &quot;http://www.81.cn/&quot; # 示例地址 try: res = requests.get(seed_url, timeout=10) soup = BeautifulSoup(res.text, 'html.parser') # 提取包含关键词的链接 links = [] for a in soup.find_all('a', href=True): text = a.get_text().strip() if any(keyword in text for keyword in KEYWORDS): absolute_url = urljoin(seed_url, a['href']) links.append(absolute_url) # 去重处理 unique_links = list(set(links)) # 保存内容(建议控制频率) for link in unique_links[:5]: # 示例仅处理前5条 save_content(link, save_path) except Exception as e: print(f'程序终止: {str(e)}') if __name__ == &quot;__main__&quot;: main() 在上述代码基础上将输txt中没有内容的删除掉,请给完整代码
03-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值