[英]Text search elements in a big python list
列表如下所示:
cell_lines = ["LN18_CENTRAL_NERVOUS_SYSTEM","769P_KIDNEY","786O_KIDNEY"]
由于涉足正则表达式,除了循环遍历每个元素并执行搜索外,我无法找到一种引人注目的方法来搜索列表中的各个字符串。
如何有效地检索包含“ KIDNEY”的索引(因为我有一个长度为数千的列表)?
进行列表理解 :
[line for line in cell_lines if "KIDNEY" in line]
这是O(n)
因为我们检查列表中的每个项目以包含KIDNEY
。
如果您经常需要进行类似的查询,则应该考虑重新组织数据,并按KIDNEY
类别对字典进行分组:
{
"KIDNEY": ["769P_KIDNEY","786O_KIDNEY"],
"NERVOUS_SYSTEM": ["LN18_CENTRAL_NERVOUS_SYSTEM"]
}
在这种情况下,每个“按类别”查找都将花费“恒定”时间。
您可以使用set
而不是list
因为它会在恒定时间内执行查找。
from bisect import bisect_left
def bi_contains(lst, item):
""" efficient `item in lst` for sorted lists """
# if item is larger than the last its not in the list, but the bisect would
# find `len(lst)` as the index to insert, so check that first. Else, if the
# item is in the list then it has to be at index bisect_left(lst, item)
return (item <= lst[-1]) and (lst[bisect_left(lst, item)] == item)
稍微修改上面的代码将为您带来很好的效率。
这是Python中可用的数据结构以及时间复杂度的列表。
https://wiki.python.org/moin/TimeComplexity
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.