将Counter中的值分配给列表

假设我有以下列表:

l1 = ['Hello', 'world', 'world']
l2 = ['Hello', 'world', 'world', 'apple']

因为l1我将不同的元素计算为:

Counter(l1)

这给出了:

Counter({'Hello': 1, 'world': 2})

现在我想通过l2并将上面的值分配给它,以便我得到:

[1,2,2,0]

正如您所看到的,apple我们分配了 0,因为计数器中没有它的值。我想知道我该怎么做?

回答

您可以像这样使用列表理解。

from collections import Counter

l1 = ['Hello', 'world', 'world']
l2 = ['Hello', 'world', 'world', 'apple']

c1 = Counter(l1)

res = [c1[i] for i in l2]
print(res)

输出

[1, 2, 2, 0]

旧解决方案(在 user2357112 评论之前支持 Monica)

res = [c1.get(i, 0) for i in l2]

  • No point using `get` - `Counter` indexing already works like that anyway.

以上是将Counter中的值分配给列表的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>