[
168
]
Like dictionaries, Python lists use an extremely efficient and well-tuned internal data
structure so we can worry about what we're storing, rather than how we're storing
it. Many object-oriented languages provide different data structures for queues,
stacks, linked lists, and array-based lists. Python does provide special instances of
some of these classes, if optimizing access to huge sets of data is required. Normally,
however, the list data structure can serve all these purposes at once, and the coder
has complete control over how they access it.
Don't use lists for collecting different attributes of individual items. We do not
want, for example, a list of the properties a particular shape has. Tuples, named
tuples, dictionaries, and objects would all be more suitable for this purpose. In some
languages, they might create a list in which each alternate item is a different type; for
example, they might write
['a', 1, 'b', 3]
for our letter frequency list. They'd
have to use a strange loop that accesses two elements in the list at once or a modulus
operator to determine which position was being accessed.
Don't do this in Python. We can group related items together using a dictionary, as
we did in the previous section (if sort order doesn't matter), or using a list of tuples.
Here's a rather convoluted example that demonstrates how we could do the frequency
example using a list. It is much more complicated than the dictionary examples, and
illustrates the effect choosing the right (or wrong) data structure can have on the
readability of our code:
import string
CHARACTERS = list(string.ascii_letters) + [" "]
def letter_frequency(sentence):
frequencies = [(c, 0) for c in CHARACTERS]
for letter in sentence:
index = CHARACTERS.index(letter)
frequencies[index] = (letter,frequencies[index][1]+1)
return frequencies
This code starts with a list of possible characters. The
string.ascii_letters
attribute provides a string of all the letters, lowercase and uppercase, in order. We
convert this to a list, and then use list concatenation (the plus operator causes two
lists to be merged into one) to add one more character, the space. These are the
available characters in our frequency list (the code would break if we tried to add
a letter that wasn't in the list, but an exception handler could solve this).
www.it-ebooks.info
Chapter 6
Do'stlaringiz bilan baham: |