w3resource

Python: Create group of similar items of a given list


42. Group Similar Items

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']]

For more Practice: Solve these Related Problems:

  • Write a Python program to group similar items from a list into sublists based on a custom equality function using itertools.groupby.
  • Write a Python program to partition a list into groups of similar elements and then map a function to each group to compute its length.
  • Write a Python program to create an iterator that groups elements with the same property and then converts each group into a sorted list.
  • Write a Python program to use itertools.groupby to cluster a list into groups and then filter out groups with a single element.

Go to:

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.

Python Code Editor:


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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.