Your solution is here:
https://docs.python.org/3.6/library/func...tml#sorted
https://docs.python.org/3/library/iterto...ls.groupby
import itertools
def bycase(word):
if word[0].isupper():
return 'uppercase'
else:
return 'lowercase'
def byfirstletter(word):
return word[0].lower()
words = ['foo', 'bar', 'Baz', 'baz', 'Bar']
# now sort bycase
words_sorted = sorted(words, key=bycase)
for key, group in itertools.groupby(words_sorted, bycase):
print('Key:', key)
for word in group:
print('Word:', word)
# now sort byfirstletter
words_sorted = sorted(words, key=byfirstletter)
for key, group in itertools.groupby(words_sorted, byfirstletter):
print('Key:', key)
for word in group:
print('Word:', word)
The more interesting part is, when you have a list like a table.
For example you have a table with cars and one row has the color.
Sorting by color example:
from itertools import groupby
from operator import itemgetter
#example data
##### col0, col1, col2
cars = [('BMW', '318i', 'blue'),
('BMW', '323i', 'blue'),
('BMW', '318i', 'black'),
('BMW', '323i', 'blue'),
('BMW', '323i', 'black'),
('BMW', '320i', 'silver'),
('BMW', '318i', 'silver'),
('BMW', '318i', 'black'),
('BMW', '323i', 'silver'),
('BMW', '320i', 'silver'),
('BMW', '323i', 'black'),
('BMW', '318i', 'blue'),
('BMW', '323i', 'blue'),
('BMW', '323i', 'blue'),
('BMW', '323i', 'blue')]
sorted_cars = sorted(cars, key=itemgetter(2)) # sort by color
for color, group in groupby(sorted_cars, itemgetter(2)): # group by color
print('Color:', color)
for manufacturer, model, color in group:
print(manufacturer, model, color)
Hope it helps. Next time you should post example data.
Ok, you edited you original post, my answer is useless in this topic.