Home > Net >  How to convert this loops into list comprehension?
How to convert this loops into list comprehension?

Time:04-20

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

CodePudding user response:

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

CodePudding user response:

data1 = {'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]}

df1 = pd.DataFrame(data1)

df1.groupby('assignment')['students'].agg(set).to_dict()

Output

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