Chalarangelo / 30-seconds-of-python

Short Python code snippets for all your development needs
https://www.30secondsofcode.org/python/p/1
Creative Commons Attribution 4.0 International
8.83k stars 1.26k forks source link

[FEATURE] replace for loop in group_by with dictionary comprehension #105

Closed defterade closed 5 years ago

defterade commented 5 years ago

Category:

Description

Also removes unnecessary list cast.

There are also unnecessary semicolons in the examples section of this function.

Current Snippet Behavior

def group_by(lst, fn):
  groups = {}
  for key in list(map(fn,lst)):
    groups[key] = [item for item in lst if fn(item) == key]
  return groups

Possible Solution

def group_by(lst, fn):
    return {key : [el for el in lst if fn(el) == key] for key in map(fn,lst)}
lock[bot] commented 4 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for any follow-up tasks.