[
167
]
"The children voted for {} ice cream".format(
Counter(responses).most_common(1)[0][0]
)
)
Presumably, you'd get the responses from a database or by using a complicated
vision algorithm to count the kids who raised their hands. Here, we hardcode it so
that we can test the
most_common
method. It returns a list that has only one element
(because we requested one element in the parameter). This element stores the name
of the top choice at position zero, hence the double
[0][0]
at the end of the call. I
think they look like a surprised face, don't you? Your computer is probably amazed
it can count data so easily. It's ancestor, Hollerith's Tabulating Machine for the 1890
US census, must be so jealous!
Lists
Lists are the least object-oriented of Python's data structures. While lists are,
themselves, objects, there is a lot of syntax in Python to make using them as painless
as possible. Unlike many other object-oriented languages, lists in Python are
simply available. We don't need to import them and rarely need to call methods
on them. We can loop over a list without explicitly requesting an iterator object,
and we can construct a list (as with a dictionary) with custom syntax. Further, list
comprehensions and generator expressions turn them into a veritable Swiss-army
knife of computing functionality.
We won't go into too much detail of the syntax; you've seen it in introductory tutorials
across the Web and in previous examples in this book. You can't code Python very
long without learning how to use lists! Instead, we'll be covering when lists should be
used, and their nature as objects. If you don't know how to create or append to a list,
how to retrieve items from a list, or what "slice notation" is, I direct you to the official
Python tutorial, post-haste. It can be found online at
http://docs.python.org/3/
tutorial/
.
In Python, lists should normally be used when we want to store several instances of
the "same" type of object; lists of strings or lists of numbers; most often, lists of objects
we've defined ourselves. Lists should always be used when we want to store items in
some kind of order. Often, this is the order in which they were inserted, but they can
also be sorted by some criteria.
As we saw in the case study from the previous chapter, lists are also very useful
when we need to modify the contents: insert to or delete from an arbitrary location
of the list, or update a value within the list.
www.it-ebooks.info
Python Data Structures
Do'stlaringiz bilan baham: |