Search code examples
pythonloopslist-comprehensionnested-loops

How to convert this loops into list comprehension?


I want to convert these loops into a list comprehension but I don't know how to do it. Can anyone help me pls?

this is the list i want to convert:

students = ['Tommy', 'Kitty', 'Jessie', 'Chester', 'Curie', 'Darwing', 'Nancy', 'Sue', 
            'Peter', 'Andrew', 'Karren', 'Charles', 'Nikhil', 'Justin', 'Astha','Victor', 
            'Samuel', 'Olivia', 'Tony']

assignment = [2, 5, 5, 7, 1, 5, 2, 7, 5, 1, 1, 1, 2, 1, 5, 2, 7, 2, 7]

x = list(zip(students, assignment))
Output = {}
for ke, y in x:
    y = "Group {}".format(y)
    if y in Output:
        Output[y].append((ke))
    else: 
        Output[y] = [(ke)] 
print(Output)

this what I have tried:

{Output[y].append((ke)) if y in Output else Output[y]=[(ke)]for ke, y in x}

Solution

  • You could do this with a nested dictionary/list comprehension:

    Output = { f'Group {group}' : [ name for name, g in x if g == group ] for group in set(assignment) }
    

    Output:

    {
      'Group 2': ['Tommy', 'Nancy', 'Nikhil', 'Victor', 'Olivia'],
      'Group 5': ['Kitty', 'Jessie', 'Darwing', 'Peter', 'Astha'],
      'Group 7': ['Chester', 'Sue', 'Samuel', 'Tony'],
      'Group 1': ['Curie', 'Andrew', 'Karren', 'Charles', 'Justin']
    }