Adryan Ziegler
Adryan Ziegler

Reputation: 49

How to freeze an iteration in loop for printing python

if i have:

alphabet = ['a', 'b', 'c', 'd', ...... ]
names = ['aaron', 'adrian', 'alan', 'brian', 'cathy', 'coby' .... ] #sorted by alphabet

How can i get output to look as:

a - aaron, adian, alan,
b - brian,
c - cathy, coby, ....
.....
.....

I tried:

  for letter in alphabet:
       print("")
       for name in names:
            if name[0] == letter:
            print(letter, " - ", name, sep=' ', end=', ', flush=True)

but It didnt work. So i want a way to freeze "letter" so it doesn't appear next to every single name.

Upvotes: 1

Views: 194

Answers (1)

Onyambu
Onyambu

Reputation: 79288

What you can do:

for letter in alphabet:
       print(letter, ' - ', end = '')
       for name in names:
            if name[0] == letter:
                print(name, sep = ', ', end = ', ')
       print()

You could also do:

from itertools import groupby
for letter, names in groupby(names, key = lambda x: x[0]):
    print(letter ,'-', ', '.join(names))

Upvotes: 1

Related Questions