Skip to content

Instantly share code, notes, and snippets.

@Rhomboid
Created December 22, 2013 06:41
Show Gist options
  • Select an option

  • Save Rhomboid/8079180 to your computer and use it in GitHub Desktop.

Select an option

Save Rhomboid/8079180 to your computer and use it in GitHub Desktop.
Python itertools.groupby example with US state capitals
from itertools import groupby
state_capitals = ['Montgomery', 'Juneau', 'Phoenix', 'Little Rock', 'Sacramento', 'Denver',
'Hartford', 'Dover', 'Tallahassee', 'Atlanta', 'Honolulu', 'Boise', 'Springfield',
'Indianapolis', 'Des Moines', 'Topeka', 'Frankfort', 'Baton Rouge', 'Augusta',
'Annapolis', 'Boston', 'Lansing', 'Saint Paul', 'Jackson', 'Jefferson City',
'Helena', 'Lincoln', 'Carson City', 'Concord', 'Trenton', 'Santa Fe', 'Albany',
'Raleigh', 'Bismarck', 'Columbus', 'Oklahoma City', 'Salem', 'Harrisburg',
'Providence', 'Columbia', 'Pierre', 'Nashville', 'Austin', 'Salt Lake City',
'Montpelier', 'Richmond', 'Olympia', 'Charleston', 'Madison', 'Cheyenne']
for letter, words in groupby(sorted(state_capitals), key=lambda c: c[0]):
print('{}:\n {}\n'.format(letter, '\n '.join(words)))
A:
Albany
Annapolis
Atlanta
Augusta
Austin
B:
Baton Rouge
Bismarck
Boise
Boston
C:
Carson City
Charleston
Cheyenne
Columbia
Columbus
Concord
D:
Denver
Des Moines
Dover
F:
Frankfort
H:
Harrisburg
Hartford
Helena
Honolulu
I:
Indianapolis
J:
Jackson
Jefferson City
Juneau
L:
Lansing
Lincoln
Little Rock
M:
Madison
Montgomery
Montpelier
N:
Nashville
O:
Oklahoma City
Olympia
P:
Phoenix
Pierre
Providence
R:
Raleigh
Richmond
S:
Sacramento
Saint Paul
Salem
Salt Lake City
Santa Fe
Springfield
T:
Tallahassee
Topeka
Trenton
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment