John W
John W

Reputation: 129

How to create a list from a list

How to get list of 'Health' and 'E.R. nurses' and its id numbers for example:

books =
[
       ['Health', 18327],
       ['Health', 19438],
       ['Health', 12549],
       ['Health', 11662],
       ['E.R.nurses', 21458],
]

Output should be like this:

[
      ['Health',18327,19438,12549,11662],['E.R.nurses',21458]
]

I tried with :

output = [ [title, n] for title, n in books if....

but 'n' can have more numbers...so I have no idea :| thank for any tips

Upvotes: 0

Views: 84

Answers (3)

j1-lee
j1-lee

Reputation: 13939

The following outputs the format you want:

import itertools
from operator import itemgetter

books = [['Health', 18327], ['Health', 19438], ['Health', 12549], ['Health', 11662], ['E.R.nurses', 21458]]

output = [[k, *(lst[1] for lst in g)] for k, g in itertools.groupby(books, key=itemgetter(0))]

print(output)
# [['Health', 18327, 19438, 12549, 11662], ['E.R.nurses', 21458]]

This uses generalized unpacking (python 3.5+).

Also it assumes (to use groupby) that in the input, lists having 'health' must be next to each other, lists having 'E.R.nurses' must be next to each other, and so on. If your data is not like that, you can put books.sort(key=itemgetter(0)) beforehand.

Upvotes: 1

Jhosef Matheus
Jhosef Matheus

Reputation: 187

you can use this code, the only difference is that it will turn your list into a dictionary, but it will separete as you want

Code:

dic = {

}

books = [
    ['Health', 18327],
    ['Health', 19438],
    ['Health', 12549],
    ['Health', 11662],
    ['E.R.nurses', 21458],
]

for book in books:
    if book[0] not in dic.keys():
        dic[book[0]] = [book[1], ]

    else:
        dic[book[0]].append(book[1])

print(dic)

Upvotes: 1

Ulises Bussi
Ulises Bussi

Reputation: 1725

I would recommend to use a dictionary, actually you can use a defaultdict:

books =[
       ['Health', 18327],
       ['Health', 19438],
       ['Health', 12549],
       ['Health', 11662],
       ['E.R.nurses', 21458],
]

from collections import defaultdict

x = defaultdict(list)

[x[key].append(val) for [key,val] in books]

Upvotes: 3

Related Questions