51
>>> names = list(open('examples/favorite-people.txt', encoding='utf-8'))
①
>>> names
['Dora\n', 'Ethan\n', 'Wesley\n', 'John\n', 'Anne\n',
'Mike\n', 'Chris\n', 'Sarah\n', 'Alex\n', 'Lizzie\n']
>>> names = [name.rstrip() for name in names]
②
>>> names
['Dora', 'Ethan', 'Wesley', 'John', 'Anne',
'Mike', 'Chris', 'Sarah', 'Alex', 'Lizzie']
>>> names = sorted(names)
③
>>> names
['Alex', 'Anne', 'Chris', 'Dora', 'Ethan',
'John', 'Lizzie', 'Mike', 'Sarah', 'Wesley']
>>> names = sorted(names, key=len)
④
>>> names
['Alex', 'Anne', 'Dora', 'John', 'Mike',
'Chris', 'Ethan', 'Sarah', 'Lizzie', 'Wesley']
1. This idiom returns alist of the lines in a text file.
2. Unfortunately (for this example), the
list(open(filename))
idiom also includes the carriage returns at the
end of each line. This list comprehension uses the
rstrip()
string method to strip trailing whitespacefrom
each line. (Strings also havean
lstrip()
method to strip leadingwhitespace, and a
strip()
method which
strips both.)
3. The
sorted()
function takes a list and returns it sorted. By default, it sorts alphabetically.
4. But the
sorted()
function can also take afunction as the
key
parameter, and it sorts by that key. In this
case, thesort function is
len()
,so it sorts by
len(each item)
.Shorter names comefirst, then longer, then
longest.
What does this haveto do with the
itertools
module? I’m glad you asked.
198