我有一个包含对象的列表,即:
[{"id":"1", "name": "name1"}, {"id":"2", "name": "nam2"}, {"id":"1", "name": "name3"}]
我需要找到具有“ id”:“ 1”的列表中对象的数量,在此示例中:2
答案 0 :(得分:2)
如果collections.Counter
拥有一个key
和sorted
这样的itertools.groupby
参数,这很好,但是不幸的是没有。
我将使用collections.defaultdict
作为计数器。作为奖励,我们将获得所有不同ID的计数器:
from collections import defaultdict
li = [{"id":"1", "name": "name1"}, {"id":"2", "name": "nam2"}, {"id":"1", "name": "name3"}]
counter = defaultdict(int)
for d in li:
counter[d['id']] += 1
print(counter['1'])
# 2
print(counter['2'])
# 1
更新
我似乎忽略了以下事实:您仍然可以使用collections.Counter
作为注释中提到的@RoadRunner:
from collections import Counter
li = [{"id":"1", "name": "name1"}, {"id":"2", "name": "nam2"}, {"id":"1", "name": "name3"}]
print(Counter(d['id'] for d in li))
# Counter({'1': 2, '2': 1})
答案 1 :(得分:1)
您可以使用列表推导来过滤所需的数据。例如:
# Data:
l=[{"id":"1", "name": "name1"}, {"id":"2", "name": "nam2"}, {"id":"1", "name": "name3"}]
print(len([x for x in l if x['id']=='1'])) # Result: 2
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# This is the key part: you filter the list according to a condition
# (in this case: x['id']=='1').
# If all you need is the number of entries for which the condition
# holds, printing the length of the resulting list will be enough.
答案 2 :(得分:0)
对此问题有不同的看法:
import operator
a = [{'id': '1', 'name': 'name1'},
{'id': '2', 'name': 'nam2'},
{'id': '1', 'name': 'name3'}]
sum(operator.countOf(i, '1') for i in map(operator.itemgetter('id'), a))