使用 itertools.combinations 生成对时出现 Python 内存错误

标签 python list compiler-errors out-of-memory

我有一个未指定数字的 int 列表。我想找到列表中匹配特定值的两个整数之间的差异。

from itertools import combinations

#Example of a list
intList = [3, 6, 2, 7, 1]
diffList = [abs(a -b) for a, b in combinations(intList, 2)]

#Given if difference = 2    
print diffList.count(2)

代码片段有效,但是当给出更大的列表时,我收到 MemoryError。谁能告诉我代码是否有问题或错误是由于我的硬件限制造成的?

最佳答案

“更大的列表”到底有多大?如果len(intList)n,则len(diffList)将为n*(n-1)//2(一次取 2 个 n 事物的组合数)。如果 n 足够大,这将占用您的所有内存。

如果你只关心值2,

print sum(abs(a-b) == 2 for a, b in combinations(intList, 2))

是一种无论 intList 有多大都消耗很少内存的方法。但是,它仍然需要 时间len(intList) 的平方成正比。

关于使用 itertools.combinations 生成对时出现 Python 内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18906997/

相关文章:

c# - iOS C# 将 JSON 数据添加到 tableView

list - 使用 golang 的列表中最后一个元素的第 Kth

c++ - 编译器错误C2541- 'delete' : delete : cannot delete objects that are not pointers

android - 在CI服务器上Gradle构建失败,但在Android Studio中未发生

Python3 : List of strings, 其中字符串具有可变字母(不是所有位置的所有字母)

python - 了解 Pandas SettingWithCopyWarning

python - 等量合并两个列表

C++ : Undefined symbols for architecture x86_64 on MacOS Mountain Lion

javascript - 在 JavaScript 中传递变量

linux - 用户输入的Python检查日期