一个有序且可修改的集合
列表(list)把值按顺序放在方括号里:[184.0, 185.5, 183.2]。它可以放任何值,len(prices) 告诉你有多少个。每个元素都有一个位置,叫索引(index),从 0 开始计数。负索引从末尾倒数,所以 -1 是最后一个元素。访问不存在的位置会引发 IndexError。
prices = [184.0, 185.5, 183.2, 186.1]
# Reading by position
print(prices[0]) # 184.0
print(prices[-1]) # 186.1
print(len(prices)) # 4
# A list is changeable: assign to a position
prices[1] = 185.0
print(prices) # [184.0, 185.0, 183.2, 186.1]切片:取列表的一部分
prices[start:stop] 返回从 start 到 stop(不含)的新列表。省略一端就一直取到那一端:prices[:3] 是前三个,prices[-3:] 是后三个。切片超出范围不会报错,只会在末尾停下。有一个陷阱:-0 就是 0,所以 prices[-0:] 是整个列表,而不是空列表。
prices = [184.0, 185.0, 183.2, 186.1, 187.4]
# Slices are new lists
print(prices[1:3]) # [185.0, 183.2]
print(prices[:2]) # [184.0, 185.0]
print(prices[-2:]) # [186.1, 187.4]
# Going past the end is fine, but -0 is not "none"
print(prices[3:99]) # [186.1, 187.4]
print(prices[-0:]) # the whole list添加与删除
append(x) 在末尾添加一个元素,extend(items) 添加多个,insert(i, x) 把元素放到位置 i。pop() 删除并返回最后一个元素(pop(i) 是位置 i 的元素),remove(x) 删除第一个等于 x 的元素。这些方法就地修改列表并返回 None,所以 prices = prices.append(1) 会让 prices 变成 None。用 + 相加则会生成新列表。
# Changing a list in place
fills = [100, 250]
fills.append(75)
fills.extend([40, 60])
print(fills) # [100, 250, 75, 40, 60]
last = fills.pop()
fills.remove(250)
print(last, fills) # 60 [100, 75, 40]
# + builds a new list and leaves the old ones alone
both = fills + [10]
print(both, fills) # [100, 75, 40, 10] [100, 75, 40]排序
排序有两种方式。prices.sort() 就地重排列表并返回 None;sorted(prices) 不改动原列表,返回一个新的已排序列表,并且可接受任何可迭代对象。两者都支持 reverse=True(从大到小)和 key=...(按其他依据排序,如 key=len)。当其他代码可能还要用原来的顺序时,优先用 sorted。
# sorted() returns a new list, sort() changes the old one
prices = [185.0, 183.2, 187.4, 184.0]
ranked = sorted(prices, reverse=True)
print(ranked) # [187.4, 185.0, 184.0, 183.2]
print(prices) # [185.0, 183.2, 187.4, 184.0] (unchanged)
prices.sort()
print(prices) # [183.2, 184.0, 185.0, 187.4]两个名字,一个列表
backup = prices 不会复制列表:两个名字指向同一个对象,改动其中一个,另一个也会变。用 prices.copy()、list(prices) 或切片 prices[:] 得到真正的(浅)拷贝。函数同理:对参数调用 .append、.sort 或 .pop 的函数也会改动调用者的列表,而调用者很少预期到这一点。
# A second name is not a copy
prices = [184.0, 185.0]
alias = prices
alias.append(186.0)
print(prices) # [184.0, 185.0, 186.0]
# A real copy is independent
backup = list(prices)
backup.append(187.0)
print(prices) # [184.0, 185.0, 186.0]
print(backup) # [184.0, 185.0, 186.0, 187.0]sorted(...)、切片和推导式,它们都会生成新列表。实验会检查你收到的列表之后是否保持不变。items[i]、items[-1]:一个元素;items[a:b]:新列表。append、extend、insert、pop、remove会修改列表,返回值没有用。sorted(items)生成新的已排序列表;items.sort()就地重排。
下一节:元组与解包,列表的定长兄弟,以及一种整洁地拆分值的方式。
实验:评分内容
- 用
top_n选出最高的价格25 分 - 用
last_n取最近的几个值25 分 - 用
moving_average计算每个价格窗口的平均值25 分 - 用
rotate把值从一端移到另一端25 分