[英]Find closest item in a sorted List of Dictionaries
I have a list of dictionaries, which are sorted on one property:我有一个字典列表,它们按一个属性排序:
[{"name":"efi", "sortedProp":"01df"},
{"name":"abe", "sortedProp":"1de9"},
{"name":"bit", "sortedProp":"e182"}...]
I want to find the closest value of sortedProp
to a given value (say for example 1dff
should return the second dict here).我想找到最接近给定值的
sortedProp
值(例如1dff
应该在这里返回第二个字典)。 I know I can use bisect
for this for optimal speed (performance is important, since the list is ~30,000 dicts long), and I've found answers for finding exact values in a list of dicts , and finding closest value in a list of ints , but I can't seem to find an answer for finding the closest value in a list of dicts.我知道我可以使用
bisect
来获得最佳速度(性能很重要,因为列表长约 30,000 个 dicts),并且我找到了在 dicts 列表中查找精确值的答案, 并在列表中找到最接近的值ints ,但我似乎无法找到在字典列表中找到最接近值的答案。
edit: I'm not asking how to sort the list of dicts, I already have done that.编辑:我不是在问如何对字典列表进行排序,我已经这样做了。 I'm asking how to find the dict that contains the closest value of
sortedProp
to a given value.我在问如何找到包含最接近给定值的
sortedProp
值的sortedProp
。
edit2: I'm using hexadecimal numbers (results from a phash run) as the sorted property, so 'closest' is defined as the Hamming distance between the two hashes.编辑 2:我使用十六进制数(来自 phash 运行的结果)作为排序属性,因此“最近”被定义为两个散列之间的汉明距离。
def takeClosestEx(myList, myNumber):
"""
Assumes myList is not sorted. Returns closest value to myNumber.
"""
return min(myList, key=lambda x:abs(int(x["sortedProp"], 16)-myNumber))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.