如何测试列表中的每个元素(使用更复杂的逻辑)?
How to test each element in a list (with little more complex logic)?
我有一个动态生成的列表:
myList = [[node1, mask1],
[node2, mask1],
[node3, mask1],
[node4, mask2],
[node5, mask2],
[node6, mask3],
[node7, mask4],
]
注意:列表中的每个 node/mask 都是软件 GUI 中的实际节点,我稍后会尝试访问和操作它们。我认为现在将它们表示为字符串可以很好地达到目的。
规则:
- 我必须在逻辑上比较列表中的每个项目才能得到结果;
保留所有节点,除了那些只连接到一种掩码的节点,在这个例子中,节点6和7需要被排除,得到以下结果:
newList = [[node1, node2, node3], [node4, node5]]
可选:我还想将每个节点的一些信息保留到已连接的掩码,以便我以后可以使用它 - 但我可以想到其他解决方案,所以它是可选的。
我尝试使用嵌套的 for 循环遍历每个元素,但遗漏了一些情况。我也尝试过使用 groupby()
,但我无法理解,因为我的 Python 知识有限。
您可以使用 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
字典还存储与每个节点列表关联的掩码。
我有一个动态生成的列表:
myList = [[node1, mask1],
[node2, mask1],
[node3, mask1],
[node4, mask2],
[node5, mask2],
[node6, mask3],
[node7, mask4],
]
注意:列表中的每个 node/mask 都是软件 GUI 中的实际节点,我稍后会尝试访问和操作它们。我认为现在将它们表示为字符串可以很好地达到目的。
规则:
- 我必须在逻辑上比较列表中的每个项目才能得到结果;
保留所有节点,除了那些只连接到一种掩码的节点,在这个例子中,节点6和7需要被排除,得到以下结果:
newList = [[node1, node2, node3], [node4, node5]]
可选:我还想将每个节点的一些信息保留到已连接的掩码,以便我以后可以使用它 - 但我可以想到其他解决方案,所以它是可选的。
我尝试使用嵌套的 for 循环遍历每个元素,但遗漏了一些情况。我也尝试过使用 groupby()
,但我无法理解,因为我的 Python 知识有限。
您可以使用 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
字典还存储与每个节点列表关联的掩码。