简体   繁体   English

Python:查找另一个列表中包含次数最少的列表元素

[英]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 ? 什么是Python的方式,以找出哪些元素elems包含至少经常items
In this example it is 'b' , because that's not contained in items at all. 在此示例中,它是'b' ,因为它根本不包含在items中。

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 ) 相对简短高效 (仅当您确定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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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