【问题标题】:Find the smallest set after merging key with empty list from one dictionary with another dictionary containing that key as value将一个字典中的带有空列表的键与另一个包含该键作为值的字典合并后找到最小的集合
【发布时间】:2021-02-07 18:46:04
【问题描述】:

我在 Python 3-x 中有两个字典:

A = {1: [9], 7: [], 14: [], 32: [9], 40: []}

B = {1: [7, 9, 10], 7: [1, 14], 14: [7, 40], 32: [9, 40], 40: [14, 32]}

对于那些空列表作为dict A中的值,我想找到作为dict B中的值包含的键。然后,将该键从dict A合并到值列表中,包含来自A的键并输出最短的一组组合键值合并。

例如, dict A 中的键 7 有一个空列表作为值。所以我们看,B 中的哪个值列表包含键 7。我们看到 1: [7, 9, 10] 和 14: [7, 40] 包含“7”作为值。因此执行合并以输出集合:{1, 7, 9, 10} 和 {14, 40, 7}。从这两个集合中,最终输出应该是最小的集合,即{14,40,7}。注意:如果两套尺寸相同,我想选择第一套。 dict A 中的键 14 和 40 也是如此。

到目前为止,我已经尝试了以下方法:

temp3 = []
for k, v in A.items():
 if len(v) == 0:
       s3 = set()
       for i,j in B.items():
           if k in j:
               lst = []
               lst.append(j)
               min_list = min(lst)
               s3 = set(min_list)
               s3.add(k)
               s3.add(i)
               temp3.append(s3)
               C = set()
               for i in temp3:
                   C = set(i)
               print("temp3 for", k, "is", C)

输出是:

temp3 for 7 is {9, 1, 7, 10}
temp3 for 7 is {40, 14, 7}
temp3 for 14 is {1, 14, 7}
temp3 for 14 is {32, 40, 14}
temp3 for 40 is {40, 14, 7}
temp3 for 40 is {40, 9, 32}

我可以执行合并。但是我无法弄清楚如何将最小的集合作为输出,如上所述。请帮忙。

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    如果您使用可迭代的候选集并在其上使用 min 会更容易:

    for a in A:
        if not A[a]:
            sets = ({b, *B[b]} for b in B if a in B[b])
            print(a, min(sets, key=len))
    

    输出:

    7 {40, 14, 7}
    14 {1, 14, 7}
    40 {40, 14, 7}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      相关资源
      最近更新 更多