Home > Enterprise >  How to create a list from a list
How to create a list from a list

Time:11-01

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

CodePudding user response:

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]

CodePudding user response:

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)

CodePudding user response:

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.

  • Related