python - 如何在python中基于dct.keys创建组

标签 python python-2.7 list function dictionary

我想根据字典键创建组。如果 key 位于多个字典中,我想创建一个组以便稍后使用。我几乎成功了,但我无法获得所需的输出。正如您在下面看到的,有两个可能的组。即 dct1 和 dct3(相同的 key 18)以及 dct 2 和 dct 4(相同的 key 8)。以下是我迄今为止创建的内容。

dct1 = {20: [(87, 6), (87, 7)],
        21: [(68, 8)],
        18: [(30, 7)],
        11: [(27, 7), (28, 7)]}

dct2 = {8: [(41, 5), (41, 6), (41, 4)],
        14: [(4, 7), (5, 7), (6, 7)],
        16: [(58, 7), (56, 7), (57, 7)]}

dct3 = {4: [(41, 5), (41, 6), (41, 4)],
        15: [(77, 7), (78, 7)],
        18: [(29, 9), (29, 8)],
        3: [(27, 7), (28, 7)]}

dct4 = {8: [(41, 5), (41, 6), (41, 4)],
        30: [(6, 9), (5, 7), (7, 9)],
        35: [(58, 7), (56, 7), (57, 7)]}

rwawl = [dct1, dct2, dct3, dct4]


def group_rooms(rectangles_with_adjacent_walls_list):
    groups = []
    for rectangle in rectangles_with_adjacent_walls_list:
        adjacent_wall_list = rectangle.keys()
        if not groups:
            groups.append([adjacent_wall_list])
        print adjacent_wall_list
        new_group_threshold = len(adjacent_wall_list)
        new_group = 0

        for adjacent_wall in adjacent_wall_list:
            for added_room in groups:
                if adjacent_wall in added_room:
                    added_room.append(adjacent_wall_list)
                    break
                else:
                    new_group += 1

            if new_group == new_group_threshold:
                groups.append([adjacent_wall_list])

    print groups
    return groups


created_groups = group_rooms(rwawl)

# MY OUTPUT:
# [[[18, 11, 20, 21]], [[18, 11, 20, 21]], [[18, 3, 4, 15]], [[8, 35, 30]]]

# DESIRED OUTPUT:
# [[[18, 11, 20, 21], [18, 3, 4, 15]], [[8, 16, 14], [8, 35, 30]]]

最佳答案

from itertools import combinations
a = [dct1, dct2, dct3, dct4]
b = [i.keys() for i in a]
print [[i,j] for i,j in combinations(b,2) if set(i) & set(j) ]

输出:

[[[18, 11, 20, 21], [18, 3, 4, 15]], [[8, 16, 14], [8, 35, 30]]]

关于python - 如何在python中基于dct.keys创建组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42467716/

相关文章:

python - 在3.4.2.0(Python 3)以上的cv2版本上使用SIFT算法

python - 替换脚本中的函数调用的最佳方法是什么?

python-2.7 - wxpython-如何从自定义wx对话框获取返回值

python - 使用空格拆分 python 列表的第一项

java - 根据字符串数组中的单词过滤列表

r - 如何将列表值列拆分为多列?

python - 使用 context.use_certificate_chain_file 时为 "key values mismatch"

Python/Pandas : If Column has multiple values, 转换为列表中具有多个值的单行

python - IDLE Python 未检测到更改

python-2.7 - 如何在 python scikit-learn 中优化精确召回曲线而不是 AUC-ROC 曲线?