Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

In order to determine the most common temperature, you must import the non-built-in Counter
function, as shown on line 12 in Listing 9.14. Using this function’s .most_common operation on the
list of temperatures values returns a two-dimensional sorted list object. (You learned about two-
dimensional lists in Hour 8, “Using Lists and Tuples.”) The temperature mode is the first item in the
dimensional list, as shown being extracted on line 18. Listing 9.15 shows the output of this script.


LISTING 9.15 Output of script0903.py


Click here to view code image


pi@raspberrypi ~ $ python3 py3prog/script0903.py

Enter the record high temps (F) for May in Indianapolis...
Record high for May 1: 88
Record high for May 2: 85
Record high for May 3: 88
...
Maximum high temp in May: 92 F
Minimum high temp in May: 85 F
Mode high temp in May: 89 F
pi@raspberrypi ~ $

By using a dictionary in the Python scripts, you can temporarily store the temperature data so
calculations can be performed upon them. Using a dictionary also allows for easy access to any of the
stored temperatures via their key, which is the day of the month.


Understanding Python Sets


A set is a collection of elements. Unlike the elements in a dictionary, a set’s elements consist only of
values. There is no key. There are two important things to know about Python sets:


The elements in a set are unordered.
Each element is unique.

Because a set’s elements are unordered, you cannot access the set’s data via an index, as you can in a
list. However, similarly to a list, a set can contain different data types. (You learned about lists in
Hour 8.) Using a set is much more efficient than using a list.


Did You Know: That’s Cold!
A set’s data elements are mutable and thus can be changed. There is another type of
set, called a frozenset. A frozenset is immutable, and thus its elements cannot be
changed. Its values are, in essence, “frozen” as they are.

Exploring Set Basics


To create an empty set in Python, you use the built-in set function, which has the following syntax:


set_name = set()

In Listing 9.16, a set called students_in_108 is created for the “108 Python Set Fundamentals”

Free download pdf