Notes Python itertools groupby packet data processing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.