问题
We have a 2 dimensional list (for this example we have it populated with unique 6 nodes and 3 masks)
myList = [[node1, mask1],
[node2, mask1],
[node3, mask1],
[node4, mask2],
[node5, mask2],
[node6, mask3]]
Now i need to test each other somehow and generate a new list to put each node that is connected to a mask in a separate [], so i can easily access it later, but also i need to filter nodes like "node6" because "node6" is only connected to one mask (in our case with "mask3" only)
Basically i want my new list to look like this:
newList = [[node1, node2, node3], [node3, node4]]
This has been giving me headache for couple of hours now.. THANK YOU IN ADVANCE!
note: it would be nice to see also what is the most efficient way to do this
edit1: what i tried:
myList =[[node1, masks1][node2, mask1] etc..] #this is earlier dynamically populated with nodes/masks
newList= []
for i in range(len(myList)):
for j in range(len(myList[i])):
try:
if myList[i][0] in newList:
pass
elif myList[i][1] == myList[j][1] and len(myList) > 1:
newList.append([db[i][0]])
break
except IndexError:
#print 'passed error'
pass
I know this dose not makes much sense for what i asked.. my previous attempts are not saved - in this example i tried to populate each node in a newlist that is connected to the same mask twice or more time.. but this is not working as expected.
回答1:
itertools.groupby()
provides an efficient way to gather items:
from itertools import groupby
my_list = [['node1', 'mask1'],
['node2', 'mask1'],
['node3', 'mask1'],
['node4', 'mask2'],
['node5', 'mask2'],
['node6', 'mask3']]
masks_to_keep = ('mask1', 'mask2')
# create a dict keyed by mask with (node, mask) pairs
as_dict = {x[0]: list(x[1]) for x in groupby(my_list, lambda x: x[1])}
# create a list, in masks_to_keep order, of lists of nodes per mask
nodes = [[x[0] for x in as_dict[mask]] for mask in masks_to_keep]
来源:https://stackoverflow.com/questions/41421039/how-to-test-items-with-each-other-in-2-dimensional-list