gpt4 book ai didi

python - 根据字典值计算列表中字典中的项目数

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:23 25 4
gpt4 key购买 nike

我在列表中有一个字典,结构如下:

my_list = [
{
"id" : 1,
"name" : "foo",
"address" : "here"
},
{
"id" : 2,
"name" : "foo2",
"address" : "there"
},
{
"id" : 3,
"name" : "foo3",
"address" : "there"
},
]

如何获取特定地址的总数?就像我想知道地址“那里”有多少人一样。我该怎么做??

最佳答案

将 len 函数与 list_comprehension 一起使用。

>>> 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

关于python - 根据字典值计算列表中字典中的项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28924821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com