织梦CMS - 轻松建站从此开始!

欧博ABG-会员注册-官网网址

欧博Count occurrences of a substring in a list of st

时间:2025-08-23 11:18来源: 作者:admin 点击: 20 次
You can do this by using the sum built-in function. No need to use list.count as well: >>> data = ["the foo is all fooed", "the bar is all b

You can do this by using the sum built-in function. No need to use list.count as well:

>>> data = ["the foo is all fooed", "the bar is all barred", "foo is now a bar"] >>> sum('foo' in s for s in data) 2 >>>

This code works because booleans can be treated as integers. Each time 'foo' appears in a string element, True is returned. the integer value of True is 1. So it's as if each time 'foo' is in a string, we return 1. Thus, summing the 1's returned will yield the number of times 1 appeared in an element.

A perhaps more explicit but equivalent way to write the above code would be:

>>> sum(1 for s in data if 'foo' in s) 2 >>>

(责任编辑:)
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:
发布者资料
查看详细资料 发送留言 加为好友 用户等级: 注册时间:2025-09-05 06:09 最后登录:2025-09-05 06:09
栏目列表
推荐内容