【问题标题】:Speed up python list search (Nested for loops)加速 python 列表搜索(嵌套 for 循环)
【发布时间】:2018-01-16 18:03:12
【问题描述】:

我目前正在努力将一些 excel 工作表转移到 python 自动化,并且遇到了速度问题。

我有一个列表列表,其中包含大约 10.000 个列表,每个列表有 20 列左右。我还有一个帐号列表(100.000 个数字)

如果列表中的帐号与帐户列表中的一个匹配,我希望遍历我的列表列表,然后从列表中挑选值。

通过运行这段代码,我能够得到我想要的结果,但是速度非常慢。

calc = 0
for row in listOfLists:
    if row[1] in Accounts:
        calc += row[8]

关于如何优化速度的任何想法?

【问题讨论】:

  • 你试过列表理解吗?
  • @thefourtheye 为什么在这种情况下您希望列表理解有所帮助?
  • 其实他想要的是它的精简版@thefourtheye

标签: python loops optimization


【解决方案1】:

Accounts 设为set。包含检查是O(1) for sets, but O(N) for lists。您整个过程的时间复杂度将从O(M*N) 降低到O(M+N)。您可以进一步将sum 与条件generator expression 一起使用:

account_set = set(Accounts)
calc = sum(row[8] for row in listOfLists if row[1] in account_set)

【讨论】:

  • 是关于你使用 sum 的,这个答案很完美!
【解决方案2】:

这是一种功能性方法,使用set 而非Accounts 作为@schwobaseggle 回答:

account_set = set(Accounts)
calc = reduce(lambda row: row[8] if row[1] in account_set else 0, listOfLists , 0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    相关资源
    最近更新 更多