[英]How do I write a function that accepts a string and will return a total number of certain characters in the string, without using .count?
beginner here.初学者在这里。 Trying to figure out how I can define a function that counts the total number of occurrences of certain characters in a string.
试图弄清楚如何定义一个函数来计算字符串中某些字符出现的总次数。 Say, we want to count the number of occurrences of the letters a and b.
比如说,我们要计算字母 a 和 b 出现的次数。 I need to do it within a for loop.
我需要在 for 循环中进行。 What I have so far is this.
到目前为止我所拥有的是这个。 Please let me know what I can do to make this work!
请让我知道我可以做些什么来完成这项工作!
#define functions
def ch_count(word):
total=0
for letter in word:
if letter==L1:
total=total+1
return total
#main program
L1=["a","e","y"]
print(ch_count("Merry Christmas")
You can try using a default dictionary.您可以尝试使用默认字典。 Unlike a normal dictionary, it provides a default value is a key does not exist in a dictionary.
与普通字典不同,它提供了一个默认值,即字典中不存在的键。
from collections import defaultdict
string = 'quick brown fox'
letter_count = defaultdict(int)
for letter in string:
letter_count[letter] += 1
print(letter_count)
You can use sum
:您可以使用
sum
:
string = 'Some test string'
c = 'a'
sum(x == c for x in string)
Checking for multiple characters instead:改为检查多个字符:
c = 'abc'
sum(x in c for x in string)
Or you can use collections.Counter
to find the count of each character:或者您可以使用
collections.Counter
来查找每个字符的计数:
from collections import Counter
counts = Counter(string)
counts[letter]
you could write a function which takes 2 arguments.您可以编写一个带有 2 个参数的函数。 The string to check, and the letter that we want to use to count occurrencies in the string.
要检查的字符串,以及我们想用来计算字符串中出现次数的字母。
# I will use a as a default letter
def count_occurrencies(s, letter='a'):
return sum([i == letter for i in s])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.