Group A List by The Values in Python - CodeSpeedy
Group A List by The Values in Python - CodeSpeedy
CodeSpeedy (https://www.codespeedy.com/)
Menu
List grouping based on values converts a list to the lists of list according to
the values taken as the second element. The first element will be string
followed by its values.
For example,
In this tutorial, I will take a tour of how to group a list using 2 methods.
1 of 6 11/4/22, 20:58
Group a list by the values in Python - CodeSpeedy https://www.codespeedy.com/group-a-list-by-the-values-in-p...
Output
1. [['Aisha', 'Robbie'], ['Cat', 'Andre', 'Beck'], ['Bhavs', 'Sam', 'Trina'
2 of 6 11/4/22, 20:58
Group a list by the values in Python - CodeSpeedy https://www.codespeedy.com/group-a-list-by-the-values-in-p...
%0A+++++++for+k%2Cz+in++groupby%28list%2Ckey%3Ditemgetter%281%29%29
%5D%0D%0A%0D%0Aprint%28res%29&version=4&stdinputs=)
3 of 6 11/4/22, 20:58
Group a list by the values in Python - CodeSpeedy https://www.codespeedy.com/group-a-list-by-the-values-in-p...
%0D%0A++result.append%28this_group%29%0D%0A%0D%0Aprint%28result%29&
version=4&stdinputs=)
As we can see Aisha and Robbie have scored 30 marks, so we can group
them together. Similarly, Bhavs, Sam, and Trina have scored 40 marks and
those 3 are grouped together. So we are grouping the student’s lists based
on their marks obtained.
Output
1. [['Bhavs', 'Sam', 'Trina'], ['Cat', 'Andre', 'Beck'], ['Aisha', 'Robbie'
By the following two methods, You can group a list based on the values
given.
Leave a Reply
Your email address will not be published. Required fields are marked *
Comment *
4 of 6 11/4/22, 20:58
Group a list by the values in Python - CodeSpeedy https://www.codespeedy.com/group-a-list-by-the-values-in-p...
Name *
Email *
Post Comment
« Random Binary Tree Generator using Python Check if two Date Ranges Overlap or not in Java
(https://www.codespeedy.com/random-binary-tree- (https://www.codespeedy.com/check-if-two-date-
generator-using-python/) ranges-overlap-or-not-in-java/) »
Search
Latest Articles
5 of 6 11/4/22, 20:58
Group a list by the values in Python - CodeSpeedy https://www.codespeedy.com/group-a-list-by-the-values-in-p...
Related Posts
By continuing to visit our website, you agree to the use of cookies as described
in our Cookie Policy (https://www.codespeedy.com/cookie-policy/)
6 of 6 11/4/22, 20:58