背景:对于for
循环中第一个值 的问题,以及在减少遍历和不必要的功的情况下如何更新集合。
简要描述下类
class Coin(object):
def __init__(self, introduction, worth)
self.name = name
self.worth = worth
class Gift(object):
def __init__(self, discount, name, amount):
self.discount = discount
self.name = name
self.amount = amount
class Wrapper(object):
def __init__(self, coin, gift)
self.coin = coin
self.gift = gift
Test_Wrapper = Wrapper(
coin=Coin('test', 10),
gift = [Gift(20, 'A', 2), Gift(10, 'B', 3)])
第一次需求:
返回数据格式:{'coin':{'test': 10}, 'gift':{'A':2, 'B':3}}
实现方式:
class Wrapper(object):
def __init__(self, coin, gift)
self.coin = coin
self.gift = gift
@property
def get_welfare_info(self):
# 使用namedtuple
WelfareInfo = namedtuple('WelfareInfo', 'coin gift')
welfare_info = WelfareInfo(coin={}, gift={})
if self.coin:
welfare_info.coin[self.coin.name] = self.coin.worth
if self.gift:
for item in self.gift:
# 此处合理利用字典的默认值属性,避免用if-else遍历处理
welfare_info.gift.setdefault(item.name, 0)
welfare_info.gitf[item.name] += item.amount
return welfare_info
第二次需求:
返回数据格式:{'coin':[{'name': 'test', 'worth':10}],
'gift':[{'name': A, 'amount': 2}, {'name': B, 'worth': 3}]}
实现方式:
先来看下不合理的实现:
class Wrapper(object):
def __init__(self, coin, gift)
self.coin = coin
self.gift = gift
@property
def get_welfare_info(self):
# 使用namedtuple
WelfareInfo = namedtuple('WelfareInfo', 'coin gift')
welfare_info = WelfareInfo(coin=[], gift=[])
if self.coin:
coin_info = {'name': self.coin.name, 'worth': self.coin.worth}
welfare_info.appned(coin_info)
if self.gift:
for item in self.gift:
# 此处在大循环中嵌套小循环,做了很多无用功
# 之后:name_list = set()
name_list = [item['name'] for item in welfare_info.gift]
'''对列表做 in 操作的时间复杂度是 O(n),
无论如何都不应该作为常规用法。判断 A 是否在
B 集合中,B 应该为哈希类型,Python 的哈希
类型包括字典 dict 和集合 set'''
if item.name in name_list:
for c in welfare_info.gift:
if c['name'] == item.name:
c['worth'] += item.worth
else:
gift = {'name': item['name'], 'worth':item['worth']}
welfare_info.gift.append(gift)
# 之后:name_list.add(item.name)
return welfare_info
改进之后:
class Wrapper(object):
def __init__(self, coin, gift)
self.coin = coin
self.gift = gift
@property
def get_welfare_info(self):
# 使用namedtuple
WelfareInfo = namedtuple('WelfareInfo', 'coin gift')
welfare_info = WelfareInfo(coin_info=[], gift_info=[])
Coin = namedtuple('Coin', 'info')
Gift = namedtuple('Gift', 'info')
if self.coin:
coin = Coin(info={'name': self.coin.name, 'worth': self.coin.worth})
if self.gift:
gift_info = {}
for item in self.gift:
gift_info.setdefault(item.name, Gift(info={'name':item.name, 'amount':item.amount}))
gift_info[item.name].info['amount'] += item.amount
welfare_info.gift_info.extend(gift_info.values())
return welfare_info
网友评论