w3resource

Python: Create group of similar items of a given list

Python Itertools: Exercise-42 with Solution

Write a Python program to create groups of similar items from a given list.

Sample Solution:

Python Code:

import itertools as it 

def group_similar_items(seq):
    result =  [list(el) for _, el in it.groupby(seq, lambda x: x.split('_')[0])]
    return result 

colors = ['red_1', 'red_2', 'green_1', 'green_2', 'green_3', 'orange_1', 'orange_2']
print("Original list:")
print(colors)
print("\nGroup similar items of the said list:")
print(group_similar_items(colors))

colors = ['red_1', 'green-1', 'green_2', 'green_3', 'orange-1', 'orange_2']
print("\nOriginal list:")
print(colors)
print("\nGroup similar items of the said list:")
print(group_similar_items(colors))

Sample Output:

Original list:
['red_1', 'red_2', 'green_1', 'green_2', 'green_3', 'orange_1', 'orange_2']

Group similar items of the said list:
[['red_1', 'red_2'], ['green_1', 'green_2', 'green_3'], ['orange_1', 'orange_2']]

Original list:
['red_1', 'green-1', 'green_2', 'green_3', 'orange-1', 'orange_2']

Group similar items of the said list:
[['red_1'], ['green-1'], ['green_2', 'green_3'], ['orange-1'], ['orange_2']]

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find all lower and upper mixed case combinations of a given string.

Next: Write a Python program to find maximum difference pair in a given list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/itertools/python-itertools-exercise-42.php