我有一个动态生成的列表:
myList = [[node1, mask1],
[node2, mask1],
[node3, mask1],
[node4, mask2],
[node5, mask2],
[node6, mask3],
[node7, mask4],
]
注意:列表中的每个节点/掩码都是软件GUI中的实际节点,我试图稍后访问和操作。我认为现在将它们表示为字符串,可以达到目的。
规则:
保留所有节点,除了那些只连接到一种类型掩码的节点,在本例中,node6和7,需要被排除并得到以下结果:
newList = [[node1, node2, node3], [node4, node5]]
可选:我还希望将每个节点的一些信息保存到已连接的掩码中,以便稍后使用 - 但我可以考虑其他解决方案,以便它可选。
我尝试使用嵌套for循环遍历每个元素但是错过了一些情况。我也试过使用groupby()
,但我无法弄明白,因为我的Python知识有限。
答案 0 :(得分:1)
您可以使用defaultdict
将具有相同掩码的所有节点分组到列表中:
from collections import defaultdict
myList = [['node1', 'mask1'],
['node2', 'mask1'],
['node3', 'mask1'],
['node4', 'mask2'],
['node5', 'mask2'],
['node6', 'mask3'],
['node7', 'mask4'],
]
# create a hash with key as mask
# and value as list of nodes with that mask
node_gps = defaultdict(list)
for item in myList:
node = item[0]
mask = item[1]
node_gps[mask].append(node)
print node_gps
# => {'mask4': ['node7'],
# 'mask1': ['node1', 'node2', 'node3'],
# 'mask3': ['node6'],
# 'mask2': ['node4', 'node5']}
# filter out nodes with only one match
# using list comprehension
newList = [v for k, v in node_gps.items() if len(v) > 1]
# or using for loops
newList = []
# iterate over each mask, nodes pair in node_gps
for mask, nodes in node_gps.items():
# append a node_list if it has more than 1 node
if len(nodes) > 1:
newList.append(nodes)
print newList
# [['node1', 'node2', 'node3'],
# ['node4', 'node5']]
node_gps
dict还存储与每个节点列表关联的掩码。