Today, there is a need to group such data into groups:
[(12), (23), (14), (5 5), (34 ), (26)]
After processing I may need to get this result:
[(1, (24)), (2, (36)), (3, (4,)), (5 , (5,))]
Find some ways, the last thought of the previous used in the Itertools inside the package GroupBy method, because less use so always forget. It can easily implement the grouping function, because it is inside the Itertools package, so its return is an iterator. This point to note below we write code to run.
from itertools import groupby from operator Import Itemgetterx = [(1, 2), (2, 3), (1, 4), (5, 5), (3, 4), (2, 6)]soooo = sorted (x, Key=itemgetter (0)) P = GroupBy (soooo, Key=itemgetter (0)) for i in p: print i[0], [_ [1] for _ in i[1 ]]output: 1 [2, 4] 2 [3, 6] 3 [4] 5 [5]
You can use Itemgetter or you can use the LAMDA expression directly to see yourself.
In fact, the method of the stupid point, with the default dict can also seem to achieve. The first element of a tuple that does not have a group is then appended to the key to get a dictionary.
Then use the dictionary. Keys () method to get the key to remove the weight, using the method of values to get the array. This method does not seem to need to be sorted, flattered. GroupBy are sorted before use, otherwise the effect cannot be achieved.
Reference:
Https://stackoverflow.com/questions/3749512/python-group-by Python GROUP By
Notes Python itertools groupby packet data processing