0

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

2
  • 3
    why don't you use a dictionary instead? That seems to be more fitting Commented Oct 31, 2021 at 20:12
  • Right ! Thank you Mahrkeenerh Commented Nov 1, 2021 at 9:37

3 Answers 3

3

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

It works and it's easy to understand , thanks
1

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.

1 Comment

it doesn't always 'adjancent' , but thanks it's a good code to study

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.