Python - 比较两个列表以查找计数

标签 python dictionary data-structures set

这是来自以下链接的扩展问题

Python - Find a tuple in list of lists

我一直在使用以下解决方案

# Your input data.
tuples = [(2,3), (3,6), (1,2)]
lists = [[1,2,3,4],[2,3,4,5],[2,3],[4,5,6]]

# Convert to sets just once, rather than repeatedly
# within the nested for-loops.
subsets = {t : set(t) for t in tuples}
mainsets = [set(xs) for xs in lists]

# Same as your algorithm, but written differently.
tallies = {
    tup : sum(s.issubset(m) for m in mainsets)
    for tup, s in subsets.items()
}

print(tallies)

它非常适合给定的解决方案,但是当我的列表大小= 541909元组大小= 3363671时,它需要很多时间。它已经运行了 30 分钟,但我还没有得到输出。每个列表/元组中的元素将按升序排列,我准备更改这些元素的数据结构。执行此操作最快的方法是什么?

最佳答案

通过使用 collections.defaultdict 构建字典,我看到了一些性能改进:

from collections import defaultdict

# Your input data.
tuples = [(i, i+1) for i in range(1000)]
lists = [[1,2,3,4],[2,3,4,5],[2,3],[4,5,6]] * 1000

def original(tuples, lists):
    subsets = {t : set(t) for t in tuples}
    mainsets = [set(xs) for xs in lists]

    return { tup : sum(s.issubset(m) for m in mainsets) for tup, s in subsets.items() }

def jp(tuples, lists):
    subsets = list(map(frozenset, tuples))
    mainsets = list(map(set, lists))
    d = defaultdict(int)
    for item in mainsets:
        for sub in subsets:
            if sub.issubset(item):
                d[sub] += 1
    return d

%timeit original(tuples, lists)  # 707 ms per loop
%timeit jp(tuples, lists)        # 431 ms per loop

关于Python - 比较两个列表以查找计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49854734/

相关文章:

将字符串映射到一组字符串的 Python 字典?

memory - RAM内存中的链表

algorithm - 在 O(log n) 中找到中位数

python - 如何使用 defaultdict 行为扩展 OrderedDict

python - 如何将两个日期时间数组合并到一个日期时间数组中?

python - 无法在 Anaconda 中 pip 安装包

javascript - 使用LoDash链和 map 创建组件。 .map 中的 QuoteSlides 未定义

ios - 解析来自服务器的复杂嵌套数据

python - 开泰结构 : calculated instances with a condition

Python:模块和打包 - 为什么 __init__.py 文件不在 __main__.py 之前执行?