Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get combinations of list of names sorted in an alphabetical order?

I have a list of names as:

names_list = ['Acosta Jose','Bailey Tyler','Barbosa Roberto','Calabro James','Carasone Allison','Adams Zane','Brencher Tim','Chacon Ramon','Arce Manuel']

I would like to get a combinations of names per each alphabet letter.

For example: A letter names are: ‘Acosta Jose’,’Adams Zane’,’Arce Manuel’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here required combinations are:

Acosta Jose Adams Zane
Acosta Jose Arce Manuel
Adams Zane Arce Manuel

Final Required output for given name list is:

[['Acosta Jose, Adams Zane',
  'Acosta Jose,Arce Manuel',
  'Adams Zane, Arce Manuel'],
 ['Bailey Tyler, Barbosa RobertoBailey Tyler, Brencher TimBarbosa Roberto, '
  'Brencher Tim'],
 ['Calabro James, Carasone AllisonCalabro James, Chacon RamonCarasone Allison '
  ',Chacon Ramon']]

>Solution :

The output shown in the question is rather confusing. However, the description seems to indicate that this is what’s required:

from itertools import combinations

names_list = ['Acosta Jose','Bailey Tyler','Barbosa Roberto','Calabro James','Carasone Allison','Adams Zane','Brencher Tim','Chacon Ramon','Arce Manuel']

ds = {}

for name in sorted(names_list):
    ds.setdefault(name[0], []).append(name)

output = ([[f'{a}, {b}' for a, b in combinations(e, 2)] for e in ds.values()])

print(output)

Output:

[['Acosta Jose, Adams Zane', 'Acosta Jose, Arce Manuel', 'Adams Zane, Arce Manuel'], ['Bailey Tyler, Barbosa Roberto', 'Bailey Tyler, Brencher Tim', 'Barbosa Roberto, Brencher Tim'], ['Calabro James, Carasone Allison', 'Calabro James, Chacon Ramon', 'Carasone Allison, Chacon Ramon']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading