gpt4 book ai didi

python - 列表搜索优化

转载 作者:太空狗 更新时间:2023-10-30 02:23:23 25 4
gpt4 key购买 nike

first = [(1, text, text, 1, 2, 3), 
(1, text, text, 1, 0, 3), ... (6054, text, text, 2, 2, 3)]
second = (1, 2, 3, 4, 5 ... 5412)

有没有更快的方法:

data = [x for x in first if x[0] in second]

最佳答案

试试这个:

first = [(1, text, text, 1, 2, 3), 
(1, text, text, 1, 0, 3), ... (1054, text, text, 2, 2, 3)]
second = (1, 2, 3, 4, 5 ... 5412)
second_set = set(second)
data = [x for x in first if x[0] in second_set]

假设第一个有 m 个元素,第二个有 n 个元素。

集合经过哈希处理,因此搜索它们的时间接近于 O(1),整体效率为 O(m)。搜索第二个列表的时间复杂度为 O(n),总效率为 O(m * n)。

关于python - 列表搜索优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4281679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com