繁体   English   中英

您如何计算列表中某个模式的出现次数?

[英]How do you count the occurences of a pattern in a list?

假设我有以下列表: ['b(2)','b(6)','a(3)','z(8)',b(4)]我想计算这个列表的频率包含 b(*),其中 * 是任意数字。 我将如何在 python 中实现这样的事情?

希望这可以帮助:

import re
a = ['b(2)','b(6)','a(3)','z(8)','b(4)']
count = sum([1 for i in a if len(re.findall('b\([0-9]\)',i))==1])
print(count)

如果值始终采用上述格式,则一种不使用 RegEx 的方法:

# Get the lenght of a list of items in list l if the item (i) contains b
l = ['b(2)','b(6)','a(3)','z(8)','b(4)']    
print(len([i for i in l if "b" in i]))

或者

import re
l = ['b(2)','b(6)','a(3)','z(8)','b(4)']
# Get the lenght of a list of items in list l if the item (i) matches the regex b\([0-9]\)
print(len([i for i in l if re.search(r'b\([0-9]\)', i)]))

Output:

3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM