Say I have a list like
>>> l = [-10,-10,-10,-20,-10,-10]
Given you don't know it's -20, I want to find the position and the number of -20
in one line or maybe two. Any thoughts?
Say I have a list like
>>> l = [-10,-10,-10,-20,-10,-10]
Given you don't know it's -20, I want to find the position and the number of -20
in one line or maybe two. Any thoughts?
This will find the least-common element:
>>> my_list = [-10,-10,-10,-20,-10,-10]
>>> from collections import Counter
>>> counter = Counter(my_list)
>>> min(counter, key=counter.get)
-20
To find the position, you could use my_list.index(min(counter, key=counter.get))
.
Note this will not work for the odd-one-out in a list such as [1, 2, 9999, 3, 4]
, you might like to check out my answer here for a case such as that.
Assuming that you want to find the items that appear only once:
>>> from collections import Counter
>>> l = [-10,-10,-10,-20,-10,-10]
>>> [i for i, n in Counter(l).iteritems() if n == 1]
[-20]
print min(l,key=l.count)
but its probably not that fast
from collections import Counter
from operator import itemgetter
print min(Counter(l).items(), key = itemgetter(1))[0]
would likely be faster
from itertools import takewhile
print l[len(list(takewhile(lambda x:l.count(x) != 1,l)))]
is probably the most efficient method ... well i dunno Counter should be fast too
If you are using a Python version earlier than 2.7, the Counter would not have been installed yet. If that is the case then the answer is found at Get the key corresponding to the minimum value within a dictionary
mydict = dict((elem, my_list.count(elem)) for elem in my_list)
mymin = min(mydict, key=mydict.get)
print mydict
print mymin
OUTPUT:
{-20:1, -10:5}
-20