python - Python - 列表理解中的 append() 操作导致内存气球
问题描述
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
2 GB RAM, 4 GB Swap
----
import re
fieldname_groups = ("(ip,clienthost,ip_addr)", "(username,user,id)")
srcgroup = [x.strip() for x in re.sub('[\(\)]+', '', fieldname_groups[0]).split(',')]
dstgroup = [x.strip() for x in re.sub('[\(\)]+', '', fieldname_groups[1]).split(',')]
if not srcgroup or not dstgroup: raise Exception("No srcgroup or dstgroup specified!")
# srcgroup is now ['ip', 'clienthost', 'ip_addr']
# dstgroup is now ['username', 'user', 'id']
# Now append the string '.keyword' to a copy of every string in each list
[srcgroup.append('%s.keyword' % x) for x in srcgroup]
[dstgroup.append('%s.keyword' % x) for x in dstgroup]
# srcgroup should now be ['ip', 'clienthost', 'ip_addr', 'ip.keyword', 'clienthost.keyword', 'ip_addr.keyword']
# dstgroup should be similar
每次我运行这段代码时,一旦我点击列表理解,内存就会膨胀,进程就会被终止。
我不明白这里的问题是什么;我觉得这是我一直在做的事情,但这次它不起作用,所以这可能是一个业余错误,但我会感谢任何帮助解决它。我什至尝试重写代码以使用标准 for 循环,但它仍然会爆炸。
谢谢!
解决方案
扩展列表的正确方法是使用extend
方法。
srcgroup = [x.strip() for x in re.sub('[\(\)]+', '', fieldname_groups[0]).split(',')]
srcgroup.extend(['%s.keyword' % x) for x in srcgroup])
请注意,参数 toextend
是一个新列表,而不是在srcgroup
将新元素添加到时迭代的生成器表达式,这一点至关重要srcgroup
。
在任何情况下,您都不应仅将列表推导式用于表达式的副作用。利用
for x in ...:
...
代替
[... for x in ...]
推荐阅读
- javascript - 导入 PDF 导致错误 URIError: Pathname cannot be decoded
- c - 如何禁用 proc 文件的读取或写入功能?
- java - akka system.scheduler().scheduleAtFixedRate 我可以在运行时更改 Duration.ofMinutes 的值吗?
- node.js - WebRTC/Node.js/Express 应用程序在本地工作,在 Heroku 上构建和运行,但返回“未找到”
- crystal-reports - Crystal Reports 2016 无法打开文档
- reactjs - 如何在我的反应项目中更新 node-sass 加载器?
- conda - conda-forge 和 cf-staging 通道有什么区别
- node.js - 如何通过node.js中的url发出http请求
- python - 树莓派新用户
- php - PHP 我以为我已经定义了用户名,为什么我的代码告诉我不是这样?