You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python3中统计列表中符合指定条件的元素出现次数?

统计列表中名称"james"的出现次数

针对给定列表 example = ["james:6823", "barry:8263", "henry:2344", "james2342"],需要先明确统计规则,这里分两种常见场景处理:

场景1:仅统计冒号前精确为"james"的项

如果"名称"指的是冒号分隔的前缀部分,只判断前缀是否等于"james",可以用以下代码:

example = ["james:6823", "barry:8263", "henry:2344", "james2342"]
count = 0
for item in example:
    # 处理带冒号和不带冒号的项,提取名称部分
    name = item.split(':')[0] if ':' in item else item
    if name == 'james':
        count += 1
print(count)  # 输出结果:1

场景2:统计所有包含"james"子串的项

如果只要字符串中包含"james"就算入统计,可以用更简洁的生成器表达式:

example = ["james:6823", "barry:8263", "henry:2344", "james2342"]
count = sum(1 for item in example if 'james' in item)
print(count)  # 输出结果:2

内容的提问来源于stack exchange,提问作者supervoaleh32

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 03:43:12