所以我列出了可能的元素:
elems = ['a', 'b', 'c', 'd']
然后我从第一个列表中选择了另一个随机项目列表 像(例如):
items = ['a', 'a', 'c', 'a', 'c', 'd']
在elems
中,找出items
中哪个元素最少包含的Pythonic方法是什么?
在此示例中,它是'b'
,因为它根本不包含在items
中。
答案 0 :(得分:2)
<强>短强>
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
另一个&#34;效率很高&#34;
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
答案 1 :(得分:1)
>>> 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'
答案 2 :(得分:0)
最快的方法是制作一个带有计数的字典:
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)