【问题标题】:Python nested loop comparing two lists and updating a dictionaryPython嵌套循环比较两个列表并更新字典
【发布时间】:2013-11-27 18:41:18
【问题描述】:

此代码按预期工作,但占用大量内存并且运行时间比我的代码的任何其他部分要长得多。

def function(input1, input2):
    mapping = []
    for item in input1:
        risks = {"A":0, "B":0, "C":0, "D":0, "E":0}
        temp = []
        for row in input2:
            if item in row[0]:
                for key in risks.keys():
                    if row[1] == key:
                        risks[key] += 1
        temp.append(item)
        for key in risks.keys():
            temp.append(risks[key])
        mapping.append(temp)
    return mapping

我希望找到一种更有效且内存更少的方法。 input1 是唯一字符串列表,input2 是非唯一元组列表。必须有更好的方法来做到这一点。

感谢您的帮助。

【问题讨论】:

  • 你能解释一下(用语言)你的功能应该做什么吗?
  • 或者提供某种输入输出示例……

标签: python performance list compare


【解决方案1】:

首先是一些测试数据:

import random

input1 = list(range(1000))
input2 = [
    ([random.randint(0, 1000) for _ in range(100)], random.choice("ABCDE"))
    for _ in range(10000)
]

然后我的新功能:

def newfunction(input1, input2):
    input1_map = {i: dict.fromkeys("ABCDE", 0) for i in input1}

    for row in input2:
        for i1 in set(row[0]):
            try:
                input1_map[i1][row[1]] += 1
            except KeyError:
                pass

    return [[i] + list(input1_map[i].values()) for i in input1]

这是深度 2,而不是 3,因此对于大型输入最终会快得多。

  1. 如果row[0] 不包含重复项,请将set(row[0]) 更改为仅row[0]
  2. 如果try 永远不会失败,请将其删除。
  3. 选择更好的变量名。我不知道事物代表什么,所以我在这里的名字很糟糕。
  4. 如果过于关注速度,可以对最后一条语句进行微优化,但我认为它不会有太大影响。
  5. list(input1_map[i].values()) 是不确定的。考虑一下。

供参考,这是旧版本:

def function(input1, input2):
    mapping = []
    for item in input1:
        risks = {"A":0, "B":0, "C":0, "D":0, "E":0}
        temp = []
        for row in input2:
            if item in row[0]:
                for key in risks.keys():
                    if row[1] == key:
                        risks[key] += 1
        temp.append(item)
        for key in risks.keys():
            temp.append(risks[key])
        mapping.append(temp)
    return mapping

它通过了我的测试:

function(input1, input2) == newfunction(input1, input2)
#>>> True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多