在Python中,对象的双向映射以及每对的标志值的最佳数据结构是什么?例如,让我们想象一下,我想要两个男女混合在一起.我想要一个数据结构来存储de matches,这样我就可以访问每个女人的相应男人,每个男人的相应女人,比方说,代表这对夫妇价值的数字.
关键特性是我希望以恒定的时间(大约是字典中的密钥访问时间)访问所有这些数据,而不会浪费构造的资源.
如果没有"旗帜价值"的特殊性,那么这篇文章中bidict建议的库绝对是完美的.实际上,每次我在我的全明星夫妇数据结构中添加一对,它会自动更新以避免一夫多妻制:
couples = bidict({
'leonard' : 'penny',
'howard' : 'bernadette',
'sheldon' : 'amy'
})
couples.forceput('stephen', 'amy')
print couples
>> bidict({'stephen': 'amy', 'leonard': 'penny', 'howard': 'bernadette'})
Run Code Online (Sandbox Code Playgroud)
我现在正在寻求有关实现quality功能的最有效和pythonic方式的建议,例如:
quality('stephen', 'amy')
>> 0.4
couples.forceput('sheldon', 'amy', quality = 1.0)
quality('sheldon', 'amy')
>> 1.0
quality('stephen', 'amy')
>> Raise KeyError
Run Code Online (Sandbox Code Playgroud) 我还在学习Rust,在尝试将Dikjstra作为培训项目的一部分时,我遇到了这种特殊的问题.首先我定义一个HashMap:
let mut dist: HashMap<Node, usize> = HashMap::new();
Run Code Online (Sandbox Code Playgroud)
然后:
let state = State { node: next_node.clone(), cost: cost + 1 };
let current_dist = dist.get(&state.node);
if (current_dist == None) || (state.cost < *current_dist.unwrap()) {
dist.insert(state.node.clone(), state.cost);
heap.push(state);
}
Run Code Online (Sandbox Code Playgroud)
这产生了一个编译错误,因为dist.get触发了一个不可变的借位,它在if ... {...}语句之后一直保留在范围内,特别是当我dist.insert要求一个可变的借位时.
我想我错过了一个模式或关键字,允许我这种类型的过程.现在我尝试了范围drop的开头if,以及其他current_dist评估
let current_dist;
{
current_dist = dist.get(&state.node);
}
Run Code Online (Sandbox Code Playgroud)
要么
let current_dist = {|| dist.get(&state.node)}();
Run Code Online (Sandbox Code Playgroud)
但是,在if声明之后,仍然会发生不可变借款的范围.