Python 根据字典值计算列表中字典中的项目数
我在一个列表中有一本字典,其结构如下:Python 根据字典值计算列表中字典中的项目数,python,Python,我在一个列表中有一本字典,其结构如下: my_list = [ { "id" : 1, "name" : "foo", "address" : "here" }, { "id" : 2, "name" : "foo2", "address" : "there" }, { "id" : 3, "name" : "foo3", "address" : "there" }, ] 如何获取特定地址
my_list = [
{
"id" : 1,
"name" : "foo",
"address" : "here"
},
{
"id" : 2,
"name" : "foo2",
"address" : "there"
},
{
"id" : 3,
"name" : "foo3",
"address" : "there"
},
]
如何获取特定地址的总计数?比如说,我想知道有多少人来自“那个里”。我该怎么做???您可以像下面这样使用
sum
函数,请注意,您需要在字典上循环,并检查目标键的值是否在那里!:
count = 0
for dictionary in my_list:
if dictionary["address"] == "there":
count+=1
print count
sum(1 for d in my_list if d['address']=='there')
演示:
>>> my_list = [
... {
... 'id' : 1,
... 'name' : 'foo',
... 'address' : 'here'
... },
... {
... 'id' : 2,
... 'name' : 'foo2',
... 'address' : 'there'
... },
... {
... 'id' : 3,
... 'name' : 'foo3',
... 'address' : 'there'
... },
... ]
>>> sum(1 for d in my_list if d['address']=='there')
2
您可以像下面那样使用
sum
函数,请注意,您需要在字典上循环并检查目标键的值是否在那里
!:
sum(1 for d in my_list if d['address']=='there')
演示:
>>> my_list = [
... {
... 'id' : 1,
... 'name' : 'foo',
... 'address' : 'here'
... },
... {
... 'id' : 2,
... 'name' : 'foo2',
... 'address' : 'there'
... },
... {
... 'id' : 3,
... 'name' : 'foo3',
... 'address' : 'there'
... },
... ]
>>> sum(1 for d in my_list if d['address']=='there')
2
在理解列表的同时使用len函数
>>> my_list = [
{
id : 1,
'name' : 'foo',
'address' : 'here'
},
{
id : 2,
'name' : 'foo2',
'address' : 'there'
},
{
id : 3,
'name' : 'foo3',
'address' : 'there'
},
]
>>> len([x for x in my_list if x['address'] == 'there'])
2
在理解列表的同时使用len函数
>>> my_list = [
{
id : 1,
'name' : 'foo',
'address' : 'here'
},
{
id : 2,
'name' : 'foo2',
'address' : 'there'
},
{
id : 3,
'name' : 'foo3',
'address' : 'there'
},
]
>>> len([x for x in my_list if x['address'] == 'there'])
2
您可以使用和列出理解
>>> from collections import Counter
>>> d = Counter([addr["address"] for addr in my_list])
>>> d["there"]
2
您可以使用和列出理解
>>> from collections import Counter
>>> d = Counter([addr["address"] for addr in my_list])
>>> d["there"]
2
如果某些条目可能缺少
地址
字段,您可以使用.get()
方法
sum(x.get('address') == "there" for x in my_list)
如果某些条目可能缺少
地址
字段,您可以使用.get()
方法
sum(x.get('address') == "there" for x in my_list)
你试过什么吗?遍历列表并计算有多少地址“there”到目前为止我尝试使用计数器遍历循环,但显然这给了我每个单词的计数。你试过什么吗?遍历列表并计算有多少地址“there”到目前为止我尝试使用计数器遍历循环,但很明显,这让我知道了每个单词的数量。@Dan,不客气!所以你也可以通过投票和接受答案来告诉社区@丹,不客气!所以你也可以通过投票和接受答案来告诉社区这个对我来说是新的!!谢谢,我稍后会试试这个。这个对我来说是新的!!谢谢,我稍后再试试。