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.



Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Inverts a dictionary with non-unique hashable values:

Example:

def tips_collect_dictionary(obj):
  inv_obj = {}
  for key, value in obj.items():
    inv_obj.setdefault(value, list()).append(key)
  return inv_obj
ages = {
  "Owen": 25,
  "Jhon": 25,
  "Pepe": 15,
}
print(tips_collect_dictionary(ages))

Output:

{25: ['Owen', 'Jhon'], 15: ['Pepe']}

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook