计算机科学 · 第 1 册 · 1–9 年级

Primary & Middle School Computer Science

本书暂未推出简体中文版。现有版本:English。

Primary & Middle School Computer Science · 1–9 年级

20Lists

The weather station at Hilltop, on the edge of the town, measures the rain every day. For January, that makes thirty-one numbers. A program could keep them in thirty-one variables, day1, day2, and so on to day31, but adding them up would take a line thirty-one names long, and the whole year would need 365 variables. Python keeps such numbers together, in order, under a single name.

You already know

A for loop repeats its block, and range(n) counts from 0 to n−1n - 1 (Chapter 16). A counter and a running total start at 0 and grow at each turn (Chapter 18). To find the largest card, keep the best one so far and compare it with each new card (Chapter 10).

20.1 A list holds many values in order

Definition 20.1 (List, item, index, length)

A list is a value that holds other values in order. It is written between square brackets, with commas: [0.0, 0.7, 6.9]. Each value is an item of the list. The position of an item is its index, counted from 0: L[0] is the first item, L[1] the second. The length of a list is its number of items, given by len(L).

A list is a row of cells. The indices, under the cells, run from 0 to len(rain) - 1 = 30.
A list is a row of cells. The indices, under the cells, run from 0 to len(rain)−1=30\texttt{len(rain)} - 1 = 30.

Here is the January list. A program in this chapter’s figures folder wrote it from the town’s weather table, and a test checks that the two agree.

# Rainfall at Hilltop, January 2025, in millimetres (day 1 first).
rain = [
    0.0, 0.0, 0.7, 0.0, 6.9, 0.0, 0.0, 0.0, 0.0, 3.3,
    0.0, 16.1, 0.0, 0.0, 5.9, 0.0, 3.3, 0.3, 7.7, 0.0,
    0.0, 2.8, 5.4, 0.0, 1.5, 0.0, 0.1, 0.0, 0.0, 2.3,
    0.0,
]
if __name__ == "__main__":
    print("days:", len(rain))
    print("1 January:", rain[0], "mm")
    print("12 January:", rain[11], "mm")
    print("31 January:", rain[len(rain) - 1], "mm")
Listing 20.1. January’s rainfall at Hilltop, in millimetres. code/grade-7/02-lists/listings/rain.py
$ python rain.py
days: 31
1 January: 0.0 mm
12 January: 16.1 mm
31 January: 0.0 mm
Output 20.1. The first, the twelfth and the last day.

The twelfth day has index 11, and the last day index 30, which is len(rain) - 1: an index is always one less than the day’s number. Python also counts from the end with negative indices: rain[-1] is the last item. An index past the end does not exist, and asking for it is an error:

from rain import rain

print(rain[30])
print(rain[31])
Listing 20.2. Index 31 of a list of 31 items. code/grade-7/02-lists/listings/index_error.py
$ python index_error.py
0.0
Traceback (most recent call last):
  File "~/session/index_error.py", line 4, in <module>
    print(rain[31])
          ~~~~^^^^
IndexError: list index out of range
[exit status 1]
Output 20.2. An IndexError: the indices stop at 30.

The first line of Listing 20.2 takes the list from the file rain.py, as in the remark of Chapter 19.

20.2 Walking through a list

Definition 20.2 (List traversal)

A list traversal, or walk through a list, visits its items one after another, from the first to the last. for x in L: runs its block once for each item, with x set to that item.

week = [0.0, 0.0, 0.7, 0.0, 6.9, 0.0, 0.0]
for amount in week:
    print(amount, "mm")
Listing 20.3. A walk through one week. code/grade-7/02-lists/listings/walk.py
$ python walk.py
0.0 mm
0.0 mm
0.7 mm
0.0 mm
6.9 mm
0.0 mm
0.0 mm
Output 20.3. One line per item, in order.

When the position matters too, the walk goes over the indices with range(len(L)), and reads each item as L[i]:

week = [0.0, 0.0, 0.7, 0.0, 6.9, 0.0, 0.0]
for i in range(len(week)):
    if week[i] > 0:
        print("day", i + 1, "had", week[i], "mm")
Listing 20.4. A walk over the indices. code/grade-7/02-lists/listings/positions.py
$ python positions.py
day 3 had 0.7 mm
day 5 had 6.9 mm
Output 20.4. Index 2 is day 3, index 4 is day 5.

20.3 Appending and removing

A list can change. A few instructions, written after the list’s name and a point, add or remove items.

shopping = ["bread", "milk"]
print(shopping)
shopping.append("apples")       # add at the end
print(shopping)
shopping.insert(0, "eggs")      # add at index 0
print(shopping)
shopping.remove("milk")         # remove the first "milk"
print(shopping)
last = shopping.pop()           # remove the last item and give it back
print(last, shopping)
shopping[0] = "six eggs"        # replace the item at index 0
print(shopping)
Listing 20.5. A shopping list that changes. code/grade-7/02-lists/listings/shopping.py
$ python shopping.py
['bread', 'milk']
['bread', 'milk', 'apples']
['eggs', 'bread', 'milk', 'apples']
['eggs', 'bread', 'apples']
apples ['eggs', 'bread']
['six eggs', 'bread']
Output 20.5. The list after each change.
Two of the changes, drawn without the remove, so that milk stays. insert(0, ...) puts a new item at index 0 and moves every other item one place along (their indices grow by 1); pop() takes away the last item.
Two of the changes, drawn without the remove, so that milk stays. insert(0, ...) puts a new item at index 0 and moves every other item one place along (their indices grow by 1); pop() takes away the last item.

With an index in its brackets, pop takes away the item at that index instead: pop(0) takes the first item, and the others move one place back.

20.4 Computed by walking

Most questions about a list are answered by one walk, with a variable that keeps what has been found so far: a running total, the largest value so far, or a counter of the items that pass a test.

from rain import rain

total = 0
for amount in rain:
    total = total + amount
print("total:", round(total, 1), "mm")

largest = rain[0]
for amount in rain:
    if amount > largest:
        largest = amount
print("wettest day:", largest, "mm")

dry = 0
for amount in rain:
    if amount == 0:
        dry = dry + 1
print("dry days:", dry)
Listing 20.6. Three walks through January. code/grade-7/02-lists/listings/total_max_count.py
$ python total_max_count.py
total: 56.3 mm
wettest day: 16.1 mm
dry days: 18
Output 20.6. The month’s rain, its wettest day and its dry days. round(x, 1) keeps one decimal.
A walk with a running total: above each item, the value of total once that item has been added.
A walk with a running total: above each item, the value of total once that item has been added.

To know which day was the wettest, the walk keeps the index of the best item so far rather than its value:

from rain import rain

best = 0                        # the index of the largest value so far
for i in range(1, len(rain)):
    if rain[i] > rain[best]:
        best = i
print("wettest day: January", best + 1, "with", rain[best], "mm")
Listing 20.7. The position of the largest value. code/grade-7/02-lists/listings/position_of_max.py
$ python position_of_max.py
wettest day: January 12 with 16.1 mm
Output 20.7. Index 11: the twelfth of January.
January’s rainfall at Hilltop, drawn from the list of . The dry days have no bar.
January’s rainfall at Hilltop, drawn from the list of Listing 20.1. The dry days have no bar.

20.5 A list is changed in place

append, insert, remove and pop do not make a new list: they change the list itself. A program can therefore start with an empty list, [], and fill it as it goes:

readings = []
print(readings, len(readings))
for amount in [0.7, 6.9, 3.3]:
    readings.append(amount)
    print(readings, len(readings))
Listing 20.8. Filling an empty list. code/grade-7/02-lists/listings/in_place.py
$ python in_place.py
[] 0
[0.7] 1
[0.7, 6.9] 2
[0.7, 6.9, 3.3] 3
Output 20.8. The same list grows by one item at each turn.

20.6 Exercises

Exercise 20.1 ★

With L = [4, 8, 15, 16, 23, 42], what are L[0], L[2], L[-1] and len(L)?

Solution

Solution of Exercise 20.1.

L[0] is 4, L[2] is 15 (the third item), L[-1] is 42 (the last item) and len(L) is 6.

Exercise 20.2 ★

What does this program print?

numbers = [1, 2, 3]
numbers.append(4)
numbers.pop(0)
numbers.insert(1, 9)
print(numbers)
Listing 20.9. Three changes. code/grade-7/02-lists/exercises/three_ops.py
Solution

Solution of Exercise 20.2.

[1, 2, 3, 4] after append, [2, 3, 4] after pop(0), which removes the item at index 0, and [2, 9, 3, 4] after the insert. It prints [2, 9, 3, 4].

Exercise 20.3 ★

What does for x in [3, 1, 4]: print(x * 2) print?

Solution

Solution of Exercise 20.3.

6, 2 and 8, one per line.

Exercise 20.4 ★

Write a program that prints the average daily rainfall of January at Hilltop.

Solution

Solution of Exercise 20.4.

from rain import rain

total = 0
for amount in rain:
    total = total + amount
print("average:", round(total / len(rain), 2), "mm a day")
The average daily rainfall. code/grade-7/02-lists/exercises/average.py

It prints average: 1.82 mm a day: 56.3 millimetres in 31 days.

Exercise 20.5 ★★

This program prints four numbers, then stops with an error. Why? Fix it.

temps = [-3, -7, -1, -4]
for i in range(len(temps) + 1):
    print(temps[i])
Listing 20.10. One turn too many. code/grade-7/02-lists/exercises/off_by_one.py
Solution

Solution of Exercise 20.5.

range(len(temps) + 1) counts 0, 1, 2, 3, 4, but the last index of a list of 4 items is 3: temps[4] is an IndexError. The walk must use range(len(temps)), or simply for t in temps:.

Exercise 20.6 ★★

This program should print the highest of four winter temperatures, all below zero. It prints 0. Why? Fix it.

temps = [-3, -7, -1, -4]
largest = 0
for t in temps:
    if t > largest:
        largest = t
print(largest)
Listing 20.11. The largest of four temperatures? code/grade-7/02-lists/exercises/largest_bug.py
Solution

Solution of Exercise 20.6.

largest starts at 0, which is higher than every temperature of the list: no item is ever larger, and 0 stays. But 0 is not in the list! The best so far must start with an item of the list:

temps = [-3, -7, -1, -4]
largest = temps[0]
for t in temps:
    if t > largest:
        largest = t
print(largest)
Starting with the first item. code/grade-7/02-lists/exercises/largest_fixed.py

It prints −1-1.

Exercise 20.7 ★★

Write a program that counts the January days with some rain. Check that rainy days and dry days make 31 together.

Solution

Solution of Exercise 20.7.

from rain import rain

rainy = 0
for amount in rain:
    if amount > 0:
        rainy = rainy + 1
print("rainy days:", rainy)
Counting the rainy days. code/grade-7/02-lists/exercises/rainy_days.py

It prints 13, and 13+18=3113 + 18 = 31: each day is either dry or rainy.

Exercise 20.8 ★★

Write a program that builds a new list with the January amounts above 5 millimetres, and prints it.

Solution

Solution of Exercise 20.8.

from rain import rain

heavy = []
for amount in rain:
    if amount > 5:
        heavy.append(amount)
print(heavy)
A new list of the heavy days. code/grade-7/02-lists/exercises/above5.py

It prints [6.9, 16.1, 5.9, 7.7, 5.4].

Exercise 20.10 ★★★

Write a program that builds a list with the items of another list in the opposite order, by walking through it once.

Solution

Solution of Exercise 20.10.

Each item is inserted at the front, so the last one read ends up first:

week = [0.0, 0.0, 0.7, 0.0, 6.9, 0.0, 0.3]
backwards = []
for amount in week:
    backwards.insert(0, amount)     # each new value goes in front
print(backwards)
Reversing a list. code/grade-7/02-lists/exercises/reverse.py

It prints [0.3, 0.0, 6.9, 0.0, 0.7, 0.0, 0.0].

Exercise 20.11 ★★★

Explain why the walk with largest always ends with the largest value of the list. Hint: say what largest holds after each turn.

Solution

Solution of Exercise 20.11.

Before the walk, largest is the first item: the largest of the items seen so far, since only one has been seen. At each turn, if the new item is larger, it replaces largest; if not, largest stays, and it is still at least as large as everything seen. So after each turn, largest is the largest of the items seen so far. After the last turn, every item has been seen: largest is the largest of the whole list.

Exercise 20.12 ★★★

Write a function longest_equal_run(values) that returns the length of the longest run of equal neighbouring items: 3 for [1, 2, 2, 2, 5, 5]. Check it on a few examples, the empty list among them.

Solution

Solution of Exercise 20.12.

The walk compares each item with the one before it: run counts the equal neighbours up to the current item and longest keeps the record. An empty list has no run at all: it is the special case tested first, and the fourth check.

def longest_equal_run(values):
    if len(values) == 0:
        return 0
    longest = 1
    run = 1
    for i in range(1, len(values)):
        if values[i] == values[i - 1]:
            run = run + 1
        else:
            run = 1
        if run > longest:
            longest = run
    return longest


print("expected 3, got", longest_equal_run([1, 2, 2, 2, 5, 5]))
print("expected 1, got", longest_equal_run([4, 3, 4]))
print("expected 4, got", longest_equal_run([7, 7, 7, 7]))
print("expected 0, got", longest_equal_run([]))
The longest run of equal neighbours. code/grade-7/02-lists/exercises/longest_equal.py

20.7 Problem: Dry Spells at Hilltop

Problem 20.1

Weekend problem — the longest dry spell of the year

A dry spell is a run of days in a row with no rain at all. Gardeners and farmers watch them closely.

Part I — By hand, with the January list of Listing 20.1.

  1. Which day was the wettest, and how much rain fell?
  2. How many days were dry?
  3. Find the longest run of dry days in a row. On which day does it start?
  4. How did you do it? Describe your method as a walk, with what you keep in your head at each day.

Part II — A program for January.

from rain import rain

longest = 0
longest_end = 0
run = 0                          # dry days in a row, up to today
for i in range(len(rain)):
    if rain[i] == 0:
        run = run + 1
        if run > longest:
            longest = run
            longest_end = i
    else:
        run = 0
start = longest_end - longest + 1
print("longest dry run:", longest, "days, from January", start + 1)
Listing 20.12. The longest dry run of January. code/grade-7/02-lists/listings/dry_spell.py
  1. What does run hold after each day? Why is it set back to 0 on a rainy day?
  2. Why does line 11 keep the index of the last day of the run, and how does line 14 find its first day?
  3. Run the program. Does it agree with your answer to question 3?
  4. If two dry runs have the same length, which one does the program report? Why?

Part III — The whole year. The file hilltop_2025.py, written by the same script, holds the rainfall of every day of 2025 in one list of 365 items, and month_days, the number of days of each month.

from hilltop_2025 import month_days, rain

names = ["January", "February", "March", "April", "May", "June", "July",
         "August", "September", "October", "November", "December"]


def date(day):
    """Day 0 of the year is 1 January; give the month and the day of the month."""
    month = 0
    while day >= month_days[month]:
        day = day - month_days[month]
        month = month + 1
    return f"{day + 1} {names[month]}"


longest = 0
longest_end = 0
run = 0
for i in range(len(rain)):
    if rain[i] == 0:
        run = run + 1
        if run > longest:
            longest = run
            longest_end = i
    else:
        run = 0
start = longest_end - longest + 1
print("days in 2025:", len(rain))
print("longest dry spell:", longest, "days")
print("from", date(start), "to", date(longest_end))
Listing 20.13. The longest dry spell of 2025. code/grade-7/02-lists/listings/dry_year.py
  1. The function date turns an index of the year into a date. What does it return for the index 0? For 31? For 58 and 59?
  2. Run the program. How long was the longest dry spell of 2025, and when was it?
  3. Could the program find a dry spell that starts in one month and ends in the next? Why is it easier with one list for the year than with twelve lists, one per month?
  4. State the result.
Solution

Solution of Problem 20.1.

1. The twelfth of January, with 16.1 millimetres.

2. 18 dry days (the items equal to 0.0).

3. From the 6th to the 9th: 4 dry days in a row. The other runs are shorter: 2 days (1st and 2nd, 13th and 14th, 20th and 21st, 28th and 29th), or 1 day.

4. Walk through the days, keeping two numbers in mind: the length of the dry run that ends today (one more than yesterday’s if today is dry, 0 if it rained) and the longest run met so far, with the day it ended.

5. run is the number of dry days in a row ending with the day just read. A rainy day breaks the run, so the count starts again from 0.

6. When run beats the record, the current day is the last day of the new longest run. The run has longest days and ends at index longest_end, so it starts at longest_end - longest + 1.

7. It agrees: 4 days from the 6th of January.

$ python dry_spell.py
longest dry run: 4 days, from January 6
Output 20.9. January’s longest dry run.

8. The first one: the record is beaten only by a strictly longer run (run > longest), so a run of the same length does not replace it.

9. Index 0 gives 1 January. For 31, the loop takes away January’s 31 days: 1 February. For 58: 58−31=2758 - 31 = 27, less than 28, so 28 February; for 59: 59−31−28=059 - 31 - 28 = 0, so 1 March.

10. The program prints the year’s result:

$ python dry_year.py
days in 2025: 365
longest dry spell: 11 days
from 10 August to 20 August
Output 20.10. The longest dry spell of 2025 at Hilltop.

11. Yes: the year is one list, so a run simply goes on from the last day of a month to the first day of the next. With twelve lists, a walk would have to carry run from one list into the next, and a run that crosses two months would be easy to cut in two by mistake.

12. Result. The longest dry spell of 2025 at Hilltop lasted 11 days, from 10 August to 20 August, as Output 20.10 shows.

本章定义的术语

在术语表中查看全部 1050 个术语