【问题标题】:Python (large) lists and unique combinations: smartest way to do themPython(大)列表和独特组合:最聪明的方法
【发布时间】:2017-07-25 17:10:37
【问题描述】:

我刚刚阅读了这里的页面:Get unique combinations of elements from a python list

批准的解决方案有效...

... 但它只适用于“small”列表(例如 100 个元素)。

我有一个“大”字符串列表(100 万个元素),我得到了臭名昭著的"MemoryError" 异常。

在非常大的列表中获得独特组合的最佳方法是什么?

提前致谢

【问题讨论】:

  • 你没有。这是个坏主意。
  • 组合的大小是多少?很快,您将获得比您希望处理的更多的数据
  • 组合大小为“2”
  • 根据您的 1M 元素中有多少确实是唯一的,您也许可以简单地 uniques = tuple(set(elements)) 并获得 uniques 中元素的组合?
  • 谢谢,这成功了。

标签: python list python-3.x combinations ram


【解决方案1】:

根据inspectorG4dget's comment 和linked answer,如果您的初始列表中的大量值重复,请先通过set 将它们过滤掉,然后找到您的组合。

from itertools import combinations

elements = [gigantic list]

uniques = tuple(set(elements))
combos = [','.join(str(thing) for thing in combo) for combo in combinations(uniques, 2)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多