【问题标题】:Get the key value if the list element in two dicts shares any tuple如果两个dict中的列表元素共享任何元组,则获取键值
【发布时间】:2021-02-01 03:27:12
【问题描述】:

我有两个字典(ab)。

每个都有许多具有不同长度列表的键。每个列表都有多个元组。

如果对应列表有任何与b 共享的元组,不管b 的键值如何,是否有任何快速的方法来获取a 的键?

示例如下:

b = {41: [(37, 15), (36, 17), (36, 16), (35, 16), (36, 15)],
     42: [(40, 15), (44, 15), (40, 18), (44, 16)]}
a = {38: [(36, 18), (37, 15), (35, 16)],
     39: [(57, 0), (54, 0), (55, 0), (56, 0)]}

def test_overlap(a, b):
    overlap = frozenset(b).isdisjoint(a)
    return not overlap

list_remove = []
for id_b, b_i in b.items():
    for id_a, a_i in a.items():
        if test_overlap(a[id_a], b[id_b]):
            list_remove.append(id_a)

list_remove=list(set(list_remove))
print(list_remove)

# Output: [38]

【问题讨论】:

    标签: python list dictionary tuples intersection


    【解决方案1】:

    b 中的所有元组中创建一个集合,并使用它来过滤a 的项目:

    b = {41: [(37, 15), (36, 17), (36, 16), (35, 16), (36, 15)],
         42: [(40, 15), (44, 15), (40, 18), (44, 16)]}
    a = {38: [(36, 18), (37, 15), (35, 16)],
         39: [(57, 0), (54, 0), (55, 0), (56, 0)]}
    
    tb = set().union(*b.values())
    r  = [ka for ka,ta in a.items() if not tb.isdisjoint(ta)]
    
    print(r) # [38]
    

    【讨论】:

    • 这比我的建议和 OP 的要快得多。
    • 谢谢!它为我的大型数据集改进了很多;)
    猜你喜欢
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 2012-08-21
    • 2015-05-03
    • 1970-01-01
    相关资源
    最近更新 更多