【问题标题】:Get list value by comparing values通过比较值获取列表值
【发布时间】:2020-07-07 07:03:23
【问题描述】:

我有一个这样的列表:

    data.append(
        {
            "type": type,
            "description": description,
            "amount": 1,
        }
    )

每次有一个新对象时,我都想检查列表中是否已经存在具有相同描述的条目。如果有,我需要在金额上加 1。

我怎样才能最有效地做到这一点?唯一的方法是遍历所有条目吗?

【问题讨论】:

  • 您可以将数据作为字典,并以描述为关键。
  • 我会说将描述值作为键是一个坏主意,因为描述可以是任意长度
  • @bigbounty 我现在把它当作一个值了吗?你到底什么意思?感谢您的帮助!
  • @ewong 正如 bigbounty 提到的那样,这并不理想。描述长度可以是 250 个字符。
  • 在这种情况下,您总是可以将数据作为字典,并将描述的哈希作为键。

标签: python django list


【解决方案1】:

我建议将data 设为字典并将描述用作键。

如果您担心使用字符串作为键的效率,请阅读:efficiency of long (str) keys in python dictionary

例子:

data = {}
while loop():  # your code here
    existing = data.get(description)
    if existing is None:
        data[description] = {
            "type": type,
            "description": description,
            "amount": 1,
        }
    else:
        existing["amount"] += 1

在任何一种情况下,您都应该首先对这两种解决方案(另一种是迭代方法)进行基准测试,然后再得出有关效率的任何结论。

【讨论】:

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