Linguist 278: Programming for Linguists (Stanford Linguistics, Fall 2021)

Sorting

Sorting objects of different types

sorted(['b', 'c', 'a']) # Returns  ['a', 'b', 'c']

sorted("bca")           # Returns  ['a', 'b', 'c']

sorted(('b', 'c', 'a')) # Returns  ['a', 'b', 'c']

# For dicts, sorting is by keys:
d = {'b': True, 'c': False, 'a': True}

sorted(d)               # Returns  ['a', 'b', 'c']  

# Sorting dict items:
d = {'b': True, 'c': False, 'a': True}

sorted(d.items())       # Returns  [('a', True), ('b', True), ('c', False)]

Reverse

Use the reverse keyword; works with any sortable object:

sorted(['b', 'c', 'a'], reverse=True) # Returns  ['c', 'b', 'a']

Sorting in other ways

sorted(['aaa', 'cc', 'b'], key=len)   # Returns  ['b', 'cc', 'aaa'] 

sorted(['aaa', 'cc', 'b'], key=len, reverse=True)   # Returns  ['aaa', 'cc', 'b']


def vowel_count(x):
    import re
    vowels = "aeiou"
    regex = re.compile(r"[{}]".format(vowels), re.I)
    m = regex.findall(x)
    return len(m)

sorted(['Xe', 'XaXaX', 'b'], key=vowel_count)   # Returns  ['b', 'Xe', 'XaXaX']