我想根据字典键创建组。如果 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/