gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:30:12 27 4
gpt4 key购买 nike

我想根据字典键创建组。如果键在不止一本字典中,我想创建一个我以后可以使用的组。我几乎成功了,但无法获得所需的输出。正如您在下面看到的,有两个可能的组。即 dct1 和 dct3(相同的键 18)以及 dct 2 和 dct 4(相同的键 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/

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