简体   繁体   English

在 Python 中返回(副本)具有给定 id 的二维列表的一行的最有效(最快)方法是什么?

[英]What is the most efficient (quickest) way to return (a copy of) a row of a two-dimensional list with a given id in Python?

What is the most efficient (quickest) way to return (a copy of) a row of a two-dimensional list with a given id in Python?在 Python 中返回(副本)具有给定 id 的二维列表的一行的最有效(最快)方法是什么? The first element of each row is an ID (string).每行的第一个元素是一个 ID(字符串)。 My function needs to search two-dimensional list for the row with the matching ID and return a copy of that row.我的函数需要在二维列表中搜索具有匹配 ID 的行并返回该行的副本。 If there is no match, it should return None.如果没有匹配,它应该返回 None。

If you're doing it only once, iterating over the list and checking the first element would be the best.如果你只做一次,迭代列表并检查第一个元素将是最好的。

If you can pre-process the table, I suggest converting into a dictionary first:如果可以对表进行预处理,建议先转换成字典:

d = {row[0]: row for row in lst}

and then searching:然后搜索:

d.get(id)

Slow list iteration (If you can't use a dict, as you specified in comments section):慢列表迭代(如果您不能使用字典,如您在评论部分指定的那样):

for row in lst:
    if row[0] == id:
        break
else:
    row = None

If you really want to do this without changing the model you will need to do an O(n) search, but I highly question opting for this choice if you really want to optimize for speed as you mention in the description:如果您真的想在不更改模型的情况下执行此操作,则需要进行O(n)搜索,但如果您真的想按照描述中提到的速度优化,我强烈质疑选择此选项:

import copy


def find_element(data, id):
    for entry in data:
        if entry[0] == id:
            return copy.copy(entry)
    return None    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM