如何在Python中计算具有特定值的字典项?



我想打印并统计出生于1973,1980年的"男性"用户。有没有办法在"生日"值中搜索"1973"one_answers"1980",以便我也可以计算它们?

def getMen():
count = 0
users = [
{'name': 'Bronn', 'gender': 'male', 'birthday': '1973-03-23'},
{'name': 'Reigar', 'gender': 'male', 'birthday': '1973-11-03'},
{'name': 'Eiegon', 'gender': 'male', 'birthday': '1963-11-03'},
{'name': 'Sansa', 'gender': 'female', 'birthday': '2012-11-03'},
{'name': 'Jon', 'gender': 'male', 'birthday': '1980-11-03'},
{'name': 'Robb', 'gender': 'male', 'birthday': '1980-05-14'},
{'name': 'Tisha', 'gender': 'female', 'birthday': '2012-11-03'},
{'name': 'Rick', 'gender': 'male', 'birthday': '2012-11-03'},
{'name': 'Joffrey', 'gender': 'male', 'birthday': '1999-11-03'},
{'name': 'Edd', 'gender': 'male', 'birthday': '1973-11-03'}
]
for user in users:
if user['gender']=='male':
count +=1
print(user)
print(count)
getMen()

您可以提取年份作为生日的子字符串,然后进行比较:

for user in users:
if user['gender']=='male' and user['birthday'][0:4] in ['1973', '1980']:
count +=1
print(user)

您可以像下面这样过滤列表并获取列表长度以查找计数:

count = len(
[
user
for user in users
if user["gender"] == "male" and user["birthday"].startswith("1973")
]
)

相关内容

  • 没有找到相关文章

最新更新