首页 > 解决方案 > 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 循环,但它仍然会爆炸。

谢谢!

标签: pythonpython-3.xpython-3.5

解决方案


扩展列表的正确方法是使用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 ...]

推荐阅读