一组固定的值
元组(tuple)像是创建后不能再改变的列表。用逗号创建,通常加圆括号:("AAPL", 184.25, 184.5)。它适合表示各部分含义固定的小记录,比如一条报价或一笔成交。可以像列表一样按索引读取,但给某个位置赋值会引发 TypeError。只有一个元素的元组需要结尾逗号 (5,),因为 (5) 只是数字 5。
quote = ("AAPL", 184.25, 184.5)
# Reading works like a list
print(quote[0], len(quote)) # AAPL 3
# Changing does not
try:
quote[1] = 185.0
except TypeError as error:
print("tuples are fixed:", error)
# One item needs a trailing comma
print(type((5,)), type((5))) # <class 'tuple'> <class 'int'>解包:给每个部分起名字
解包(unpacking)一次把元组(或任何序列)的各部分赋给多个名字:symbol, bid, ask = quote。名字的个数必须与元素个数一致,否则 Python 会引发 ValueError。与 quote[0]、quote[1]、quote[2] 相比,名字能说明每个部分的含义,所以解包通常比索引更清晰。它还提供了不用临时变量的经典交换写法:a, b = b, a。
# Unpack a quote into named parts
quote = ("AAPL", 184.25, 184.5)
symbol, bid, ask = quote
print(symbol, round(ask - bid, 2)) # AAPL 0.25
# Swap two values without a temporary
bid, ask = ask, bid
print(bid, ask) # 184.5 184.25
# The count must match
try:
symbol, bid = quote
except ValueError as error:
print("wrong count:", error)用 * 接收剩余部分
在某个名字前加 *,它会以列表形式收集所有剩余部分:first, *rest = prices 或 first, *middle, last = prices。只允许一个带星号的名字,普通名字各自需要一个元素。不需要的部分可以用 _,例如 first, *_, last = prices。
# * collects what is left, as a list
prices = [184.0, 185.0, 183.2, 186.1]
first, *rest = prices
print(first, rest) # 184.0 [185.0, 183.2, 186.1]
first, *_, last = prices
print(first, last) # 184.0 186.1循环、返回值与排序中的解包
只要是给名字赋值的地方都能解包:for 循环(for symbol, price in quotes)、推导式,以及用 return a, b 返回多个值的函数的结果(其实返回的是一个元组)。元组还会逐项比较:先比第一项,相同再比第二项,所以对 (price, symbol) 元组的列表排序时,先按价格排,价格相同再按代码排。
# Return several values, unpack them in the caller
def spread_and_mid(bid, ask):
return ask - bid, (bid + ask) / 2
spread, mid = spread_and_mid(184.25, 184.5)
print(spread, mid) # 0.25 184.375
# Tuples sort by the first item, then the second
quotes = [("AAPL", 184.5), ("MSFT", 410.2), ("GOOG", 171.0)]
by_price = sorted((price, symbol) for symbol, price in quotes)
print(by_price) # [(171.0, 'GOOG'), (184.5, 'AAPL'), (410.2, 'MSFT')]
for price, symbol in by_price:
print(symbol, price)记录用元组,集合用列表当每个部分的位置都有含义且大小固定时,用元组,如
(symbol, bid, ask)。当有许多相似的元素、可能增删时,用列表。由于元组不可变,它还能用在列表不能用的地方,例如作为字典的键,这很快就会讲到。(a, b, c):固定的一组值;可读取,不可修改。x, y = pair:解包到名字;个数必须匹配。first, *rest = items:带星号的名字把剩余部分收集为列表。
下一节:字典,用名字而不是位置来查找值。
实验:评分内容
- 用
quote_stats解包一条报价25 分 - 用
first_last取首尾两端25 分 - 用
ranked按价格给报价排名25 分 - 用
best_ask找到报价最低的交易场所25 分