英文:
Simple way of getting key depending on value from hashmap in Golang
问题
在Golang中,给定一个具有键和值的哈希映射(hashmap),最简单的方法是通过值来检索键。
例如,在Ruby中,等价的写法是:
key = hashMap.key(value)
英文:
Given a hashmap in Golang which has a key and a value, what is the simplest way of retrieving the key given the value?
For example Ruby equivalent would be
key = hashMap.key(value)
答案1
得分: 15
没有内置的函数可以做到这一点;你需要自己编写代码。下面是一个示例函数,可以用于map[string]int
类型的映射,你可以根据其他映射类型进行调整:
func mapkey(m map[string]int, value int) (key string, ok bool) {
for k, v := range m {
if v == value {
key = k
ok = true
return
}
}
return
}
用法:
key, ok := mapkey(hashMap, value)
if !ok {
panic("value does not exist in map")
}
请注意,这是一个示例函数,你可以根据自己的需求进行修改和扩展。
英文:
There is no built-in function to do this; you will have to make your own. Below is an example function that will work for map[string]int
, which you can adapt for other map types:
func mapkey(m map[string]int, value int) (key string, ok bool) {
for k, v := range m {
if v == value {
key = k
ok = true
return
}
}
return
}
Usage:
key, ok := mapkey(hashMap, value)
if !ok {
panic("value does not exist in map")
}
答案2
得分: 11
重要的问题是:你需要查找值的次数有多少?
如果你只需要查找一次,那么你可以迭代键值对,并保留与值匹配的键(或键)。
如果你需要经常进行查找,我建议你创建另一个映射,将键和值反转(假设所有键都映射到唯一的值),并将其用于查找。
英文:
The important question is: How many times will you have to look up the value?
If you only need to do it once, then you can iterate over the key, value pairs and keep the key (or keys) that match the value.
If you have to do the look up often, then I would suggest you make another map that has key, values reversed (assuming all keys map to unique values), and use that for look up.
答案3
得分: 0
我正在开发一个基于比特币的服务器,并且有一个常量和字节码列表用于支付脚本。在C++版本中,它既有带有代码的标识符,又有另一个函数返回字符串版本。所以只需要取原始版本,将操作码作为字符串键,字节作为值,然后反转顺序,这样就不需要太多额外的工作。唯一让我感到困扰的是值上的重复键。但是由于这些只是true和false,重叠的是零和一,字符串切片的第一个索引都是数字和操作码,而真值是第二个索引。
每次迭代列表以识别要执行的脚本命令将导致平均测试50%的映射元素。更简单的方法是使用反向查找表。在一个完整的区块上,执行脚本可能需要多达10,000次,所以节省内存而代价是处理能力是没有意义的。
英文:
I am in the midst of working on a server based on bitcoin and there is a list of constants and byte codes for the payment scripts. In the C++ version it has both identifiers with the codes and then another function that returns the string version. So it's really not much extra work to just take the original, with opcodes as string keys and the byte as value, and then reverse the order. The only thing that niggles me is duplicate keys on values. But since those are just true and false, overlapping zero and one, all of the first index of the string slice are the numbers and opcodes, and the truth values are the second index.
To iterate the list every time to identify the script command to execute would cost on average 50% of the map elements being tested. It's much simpler to just have a reverse lookup table. Executing the scripts has to be done maybe up to as much as 10,000 times on a full block so it makes no sense to save memory and pay instead in processing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论