[英]Pythonic way to find elementa of a python list that are not contained in another python list
[英]Python: Find the list element that is contained least times in another list
因此,我列出了可能的要點:
elems = ['a', 'b', 'c', 'd']
然后,我從第一個列表中選擇了另一個隨機項目列表。
類似於(例如)的東西:
items = ['a', 'a', 'c', 'a', 'c', 'd']
什么是Python的方式,以找出哪些元素elems
包含至少經常items
?
在此示例中,它是'b'
,因為它根本不包含在items
中。
短
print(min(elems, key=items.count)) # b
相對簡短高效 (僅當您確定elems
沒有重復項時才使用它)
from collections import Counter
c = Counter(items + elems)
print(c.most_common()[-1][0]) # b
高效
d = {x: 0 for x in elems}
for x in items:
d[x] += 1
print(min(d, key=d.get)) # b
另一個“效率高”
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'
最快的方法是制作一個包含數字的字典:
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.