简体   繁体   English

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

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

Assume I have the following list: ['b(2)','b(6)','a(3)','z(8)',b(4)] And I want to count how often this list contains b(*), with * being any number.假设我有以下列表: ['b(2)','b(6)','a(3)','z(8)',b(4)]我想计算这个列表的频率包含 b(*),其中 * 是任意数字。 How would I achieve such thing in python?我将如何在 python 中实现这样的事情?

Hope this helps:希望这可以帮助:

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)

One way to do it without using RegEx if the values are always in the above format:如果值始终采用上述格式,则一种不使用 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]))

Or或者

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: Output:

3

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

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