简体   繁体   中英

Python: Find the list element that is contained least times in another list

So I have a list of possible elments:

elems = ['a', 'b', 'c', 'd']

Then I have another list of random items chosen from the first list.
Something like (for example):

items = ['a', 'a', 'c', 'a', 'c', 'd']

What is the Pythonic way to find out which element in elems is contained least often in items ?
In this example it is 'b' , because that's not contained in items at all.

Short

print(min(elems, key=items.count)) # b

Relatively short and efficient (only use it if you're sure there're no duplicates in elems )

from collections import Counter
c = Counter(items + elems)
print(c.most_common()[-1][0]) # b

Just efficient

d = {x: 0 for x in elems} 
for x in items:
    d[x] += 1

print(min(d, key=d.get)) # b

Another "just efficient"

from collections import defaultdict
d = defaultdict(int) 
for x in items:
    d[x] += 1

print(min(elems, key=d.__getitem__)) 
# or print(min(elems, key=lambda x: d[x])) - gives same result
>>> from collections import Counter
>>> elems = ['a', 'b', 'c', 'd']
>>> items = ['a', 'a', 'c', 'a', 'c', 'd']
>>> c = Counter(dict.fromkeys(elems, 0))
>>> c.update(Counter(items))
>>> c
Counter({'a': 3, 'c': 2, 'd': 1, 'b': 0})
>>> min(c, key=c.get)
'b'

The fastest way is to make a dictionary with counts in it:

aDict = { k:0 for k in elems }
for x in items: 
  if x not in aDict: aDict[x] = 0 
  aDict[x] += 1 

print min(aDict, key=aDict.get)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM