Collections
導入済み| English | 意味 |
|---|---|
| list/lɪst/ | リスト |
| dictionary/ˈdɪkʃənəri/ | 辞書 |
| key/kiː/ | A value used to identify or look up an associated item, such as a key in a dictionary or database. |
| tuple/ˈtuːpl/ | タプル |
| set/set/ | セット |
| aliasing/ˈeɪlɪəsɪŋ/ | 别名化 |
Which drink sells best?
- A café till records every order:
"tea","latte","tea"… 200 times a day. One variable per order would be useless. You need one name that holds many values. - Python has four built-in collections, and each one suits a different job. Choosing the right one often makes the rest of the program short.
A list keeps items in order
- A list 列表 is an ordered sequence that you can change:
marks = [72, 55, 90, 48, 81]. Positions are counted from 0, somarks[0]is72andmarks[-1], the last item, is81. - A slice takes a part:
marks[1:3]is[55, 90], from position 1 up to, but not including, position 3.len(marks)is5.
With s = [10, 20, 30, 40, 50], what is s[1:4]?
Difficulty 1/5 · 100 coins + a small bonus on first completion today
Position 1 holds 20 (counting from 0), and the slice stops before position 4, so it takes positions 1, 2 and 3.
Changing a list
marks.append(66)adds to the end;marks.remove(48)deletes the first48;marks[1] = 58replaces one item.marks.sort()sorts the list in place and returnsNone. To keep the original and get a sorted copy, writesorted(marks).
nums = [3, 1, 2]
result = nums.sort()
print(result, nums) # None [1, 2, 3]
After nums = [3, 1, 2] and nums = nums.sort(), what is nums?
Difficulty 1/5 · 100 coins + a small bonus on first completion today
sort() sorts the list in place and returns None, and that None is what gets stored in nums. Write nums.sort() alone, or nums = sorted(nums).
A dictionary looks things up by key
- A dictionary 字典 maps each key 键 to a value:
stock = {"tea": 40, "latte": 25}.stock["tea"]is40. - A missing key raises a
KeyError.stock.get("mocha", 0)returns the default0instead, so it is safe for counting.
- Count how many times each drink was ordered.
- Start with
tally = {}. For eachitemin the orders, writetally[item] = tally.get(item, 0) + 1. - For
["tea", "flat white", "tea", "latte", "tea"]the result is{'tea': 3, 'flat white': 1, 'latte': 1}. The first sighting of a drink gets0 + 1; later sightings add one more.
A tally is a dictionary
Each key is a drink and each value is how many were ordered. Step through the pairs; looking up tally["tea"] goes straight to its value without scanning the others.
The tally loop runs over ["tea", "latte", "tea", "mocha", "tea", "latte"]. What is tally["tea"] at the end?
Difficulty 2/5 · 140 coins + a small bonus on first completion today
"tea" appears three times. The first time tally.get("tea", 0) + 1 gives 1; each later sighting adds one more.
Tuples and sets
- A tuple 元组 is a fixed group, such as a point
p = (3, 4). You can unpack it,x, y = p, butp[0] = 5raises aTypeError: it cannot change. - A set 集合 holds each value once, in no fixed order:
{"tea", "latte", "tea"}has only2items. Use it to remove duplicates or to test membership quickly.
Choose the collection by the job
- Order matters, or you need positions → list. Look up a value by a name or code → dictionary.
- A fixed group of parts, such as a date or a point → tuple. Only "is it there?" and no duplicates → set.
Match each job to the best collection.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Order → list; lookup by key → dictionary; fixed parts → tuple; uniqueness → set.
Two names, one list
b = adoes not copy a list. It puts a second name on the same list, sob.append(2)changes whatashows too. This sharing is called aliasing 别名.- When you need an independent copy, make one:
b = a[:]orb = list(a).

After a = [1, 2], b = a, b.append(3), what is a?
Difficulty 1/5 · 100 coins + a small bonus on first completion today
b = a put a second name on the same list, so the change made through b shows through a. With b = a[:], a would stay [1, 2].
Don't remove items while you loop over them
- Removing from a list while a
forloop walks through it skips items: each removal shifts the later items left, but the loop still moves on to the next position. - With
m = [40, 45, 70, 30], removing every mark below 50 inside the loop leaves[45, 70], and45is missed. Build a new list instead:[x for x in m if x >= 50]gives[70].
Removing every item below 50 inside for x in m: always leaves only the items of 50 or more.
Difficulty 1/5 · 100 coins + a small bonus on first completion today
Each removal shifts the later items left, so the loop skips one. [40, 45, 70, 30] ends as [45, 70]. Build a new list with [x for x in m if x >= 50].
Marks that slip away
- Counting from 1. The first item is
[0]; the last is[len(x) - 1]or[-1]. x = x.sort().sort()returnsNone, soxis lost. Callx.sort()alone, or usesorted(x).d[key]for a key that may be missing. Used.get(key, default)or testif key in d:first.- Thinking
b = acopies. It shares; copy witha[:]when you need two lists.
d = {"tea": 2}. Which lines run without raising an error? Select all that apply.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Reading a missing key with d["mocha"] raises a KeyError. .get returns the default, in returns False, and assigning to a new key simply adds it.
You've got it
- list: ordered and changeable, positions from 0, slices
[a:b]stop beforeb. dictionary: key → value,.get(key, default)never raises. - tuple: a fixed group you can unpack. set: unique values, fast membership tests.
b = ashares one list (aliasing); copy witha[:]. Never remove from a list you are looping over; build a new one.