当前代码是否有更短的版本,用于计算数组中元素的出现次数并将其存储在字典中?
a = [1,2,2,3,4,5,2,2,1]
dic = {}
for x in a:
if x in dic:
dic[x] = dic[x] + 1
else:
dic[x] = 1
print dic
答案 0 :(得分:2)
您可以使用collections.Counter()
:
/* Flexbox on WooCommerce archive products */
.woocommerce .products ul,
.woocommerce ul.products {
display: flex;
flex-flow: row wrap;
}
.woocommerce ul.products li.product,
.woocommerce-page ul.products li.product {
display: flex;
flex-flow: column nowrap;
}
.woocommerce ul.products li.product .button {
margin-top: auto;
display: table;
}
来自文档:
答案 1 :(得分:2)
您可以使用dictionary.get(key, default)
获取密钥的值,如果密钥不存在,则会提供默认参数。
a = [1,2,2,3,4,5,2,2,1]
dic = {}
for n in a:
dic[n] = dic.get(n, 0) + 1