如何计算 Python 列表中具有特定值的字典项?
How can I count dictionary items with specific values inside list in Python?
我想打印并统计 'male' 并且出生于 1973 年、1980 年的用户。有没有办法在 'birthday' 值中搜索“1973”和“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")
]
)
我想打印并统计 'male' 并且出生于 1973 年、1980 年的用户。有没有办法在 'birthday' 值中搜索“1973”和“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")
]
)