开发者

Efficient way to find the largest key in a dictionary with non-zero value

开发者 https://www.devze.com 2022-12-08 21:24 出处:网络
I\'m new Python and trying to implement code in a more Pythonic and efficient fashion. Given a dictionary with numeric keys and values, what is the best way to find the largest key with a non-zero va开

I'm new Python and trying to implement code in a more Pythonic and efficient fashion. Given a dictionary with numeric keys and values, what is the best way to find the largest key with a non-zero va开发者_运维问答lue?

Thanks


Something like this should be reasonably fast:

>>> x = {0: 5, 1: 7, 2: 0}
>>> max(k for k, v in x.iteritems() if v != 0)
1

(removing the != 0 will be slightly faster still, but obscures the meaning somewhat.)


To get the largest key, you can use the max function and inspect the keys like this:

max(x.iterkeys())

To filter out ones where the value is 0, you can use a generator expression:

(k for k, v in x.iteritems() if v != 0)

You can combine these to get what you are looking for (since max takes only one argument, the parentheses around the generator expression can be dropped):

max(k for k, v in x.iteritems() if v != 0)


Python's max function takes a key= parameter for a "measure" function.

data = {1: 25, 0: 75}
def keymeasure(key):
    return data[key] and key

print max(data, key=keymeasure)

Using an inline lambda to the same effect and same binding of local variables:

print max(data, key=(lambda k: data[k] and k))

last alternative to bind in the local var into the anonymous key function

print max(data, key=(lambda k, mapping=data: mapping[k] and k))


If I were you and speed was a big concern, I'd probably create a new container class "DictMax" that'd keep track of it's largest non-zero value elements by having an internal stack of indexes, where the top element of the stack is always the key of the largest element in the dictionary. That way you'd get the largest element in constant time everytime.


  list=[1, 1, 2, 3,3]
  s={items:list.count(items)for items in list} ##occurrence of list 
  largest_value=max(k for k, v in s.items() if v != 0) #largest number occurrence 
  print(largest_value)
0

精彩评论

暂无评论...
验证码 换一张
取 消