本文目录导读:

在Python中分配不同场景的权重有很多方法,我来介绍几种常用的实现方式:
字典映射法(最简单)
# 使用字典直接存储权重
scenario_weights = {
'home': 0.3,
'work': 0.4,
'travel': 0.2,
'sports': 0.1
}
# 获取某个场景的权重
def get_weight(scenario):
return scenario_weights.get(scenario, 0) # 默认权重为0
print(f"工作场景权重: {get_weight('work')}") # 输出: 0.4
加权随机选择
import random
def weighted_random_choice(weights_dict):
"""根据权重随机选择场景"""
scenarios = list(weights_dict.keys())
weights = list(weights_dict.values())
return random.choices(scenarios, weights=weights, k=1)[0]
# 使用示例
scenario_weights = {
'home': 3,
'work': 4,
'travel': 2,
'sports': 1
}
# 模拟1000次选择,查看分布
results = {}
for _ in range(1000):
scenario = weighted_random_choice(scenario_weights)
results[scenario] = results.get(scenario, 0) + 1
print("1000次选择结果分布:")
for scenario, count in results.items():
print(f"{scenario}: {count}次 ({count/1000:.1%})")
场景权重类(面向对象方式)
class ScenarioManager:
def __init__(self):
self.scenarios = {}
self.total_weight = 0
def add_scenario(self, name, weight):
"""添加场景及其权重"""
self.scenarios[name] = weight
self.total_weight += weight
def get_normalized_weight(self, name):
"""获取归一化后的权重"""
if name not in self.scenarios:
return 0
return self.scenarios[name] / self.total_weight
def select_random(self):
"""根据权重随机选择场景"""
return weighted_random_choice(self.scenarios)
def get_priority(self, name):
"""获取场景优先级排名"""
sorted_scenarios = sorted(self.scenarios.items(),
key=lambda x: x[1], reverse=True)
for idx, (scenario, _) in enumerate(sorted_scenarios):
if scenario == name:
return idx + 1
return None
# 使用示例
manager = ScenarioManager()
manager.add_scenario('home', 30)
manager.add_scenario('work', 40)
manager.add_scenario('travel', 20)
manager.add_scenario('sports', 25)
print(f"工作场景归一化权重: {manager.get_normalized_weight('work'):.2f}")
print(f"体育场景优先级: 第{manager.get_priority('sports')}名")
基于条件的动态权重
def calculate_weights(context):
"""
根据上下文动态计算权重
context: 包含相关条件的字典
"""
weights = {
'home': 0.2,
'work': 0.3,
'travel': 0.25,
'sports': 0.25
}
# 根据时间调整
hour = context.get('hour', 12)
if hour < 8:
weights['home'] += 0.2
weights['work'] -= 0.1
elif 8 <= hour < 18:
weights['work'] += 0.3
weights['home'] -= 0.1
# 根据星期调整
weekday = context.get('weekday', 0)
if weekday >= 5: # 周末
weights['home'] += 0.2
weights['work'] -= 0.2
weights['travel'] += 0.1
# 归一化
total = sum(weights.values())
weights = {k: v/total for k, v in weights.items()}
return weights
# 使用示例
context = {'hour': 14, 'weekday': 3} # 周三下午2点
weights = calculate_weights(context)
print(f"周三下午2点权重分配: {weights}")
使用numpy进行权重计算
import numpy as np
class WeightedScenarios:
def __init__(self, scenarios, weights):
self.scenarios = np.array(scenarios)
self.weights = np.array(weights)
self.normalize()
def normalize(self):
"""归一化权重"""
self.weights = self.weights / self.weights.sum()
def select_batch(self, n):
"""批量选择n个场景"""
return np.random.choice(self.scenarios, size=n, p=self.weights)
def weighted_average_score(self, scores):
"""计算加权平均分"""
return np.sum(self.weights * scores)
# 使用示例
scenarios = ['home', 'work', 'travel', 'sports']
weights = [3, 4, 2, 1]
ws = WeightedScenarios(scenarios, weights)
print(f"归一化权重: {ws.weights}")
# 批量选择
selected = ws.select_batch(10)
print(f"批量选择结果: {selected}")
# 计算加权平均分(假设每个场景有个评分)
scores = np.array([80, 90, 75, 60])
avg_score = ws.weighted_average_score(scores)
print(f"加权平均分: {avg_score:.2f}")
配置文件方式
import json
# config.json
config = '''
{
"scenarios": {
"home": {"weight": 0.3, "priority": "high"},
"work": {"weight": 0.4, "priority": "high"},
"travel": {"weight": 0.2, "priority": "medium"},
"sports": {"weight": 0.1, "priority": "low"}
}
}
'''
def load_weights_from_config():
"""从配置文件加载权重"""
config_data = json.loads(config)
return config_data['scenarios']
def apply_scenario_rules(scenario_name, weight, rules):
"""应用场景规则"""
if rules.get('priority') == 'high':
weight *= 1.2 # 高优先级权重加成
elif rules.get('priority') == 'low':
weight *= 0.8 # 低优先级权重降低
return weight
# 使用示例
scenarios = load_weights_from_config()
adjusted_weights = {}
for name, config in scenarios.items():
weight = config['weight']
adjusted_weights[name] = apply_scenario_rules(name, weight, config)
print(f"调整后的权重: {adjusted_weights}")
选择建议
- 简单场景:使用字典映射法,直接存储权重
- 需要随机选择:使用
random.choices或numpy的权重采样 - 复杂业务逻辑:使用面向对象方式,封装权重管理
- 动态权重:根据时间、用户行为等条件实时计算
- 大量数据:使用numpy进行矢量化计算
根据你的具体需求选择合适的方法即可!需要我详细解释某个方法的实现细节吗?