2025-09-10:仓库迁移
This commit is contained in:
37
1.数据结构与算法/18.将名称映射到序列元素.py
Normal file
37
1.数据结构与算法/18.将名称映射到序列元素.py
Normal file
@@ -0,0 +1,37 @@
|
||||
# collection库中有一个东西叫做namedtuple,有点像结构体,可以给元组中的元素起名
|
||||
from collections import namedtuple
|
||||
|
||||
Subscribe = namedtuple('Subscriber', ["addr", "joined"])
|
||||
sub = Subscribe("suka@qq.com", "2024/07/17")
|
||||
print(sub)
|
||||
print(sub.addr)
|
||||
print(sub.joined)
|
||||
|
||||
# 可以看到,这个东西和对象有点相似,但这种操作又保留了适用于元组的所有操作,比如索引和分解
|
||||
print(sub[0])
|
||||
print(len(sub))
|
||||
addr, joined = sub
|
||||
print(addr, joined)
|
||||
|
||||
# 如果我们获取的数据总是list类型,不是标准的json数据,那这东西就很有用
|
||||
# 比如返回的数据是这种东西: data = [0,1,1,3,2,6]
|
||||
# 如果是这种非标数据,普通代码处理长这样:
|
||||
def compute_cost(records):
|
||||
total = 0.0
|
||||
for rec in records:
|
||||
total += rec[1] * rec[2]
|
||||
|
||||
return total
|
||||
|
||||
# 这造成一个问题,鬼知道rec[1]和rec[2]是什么东西,代码可读性很傻逼;
|
||||
# 所以我们可以在拿到数据的时候先标准化一下
|
||||
Stock = namedtuple("Stock", ['name', 'share', 'price'])
|
||||
def compute_cost(records):
|
||||
total = 0.0
|
||||
for rec in records:
|
||||
stock = Stock(*rec)
|
||||
total += stock.share * stock.price
|
||||
|
||||
return total
|
||||
|
||||
# 当然如果返回的已经是对象了,那就没有做namedtuple的必要了,在不想用类的时候可以用这东西替代字典
|
Reference in New Issue
Block a user