如何统计字符串中某个字符出现的次数?
例如,在字符串“Mary had a little lamb”中,“a”出现了4次。
我不知道什么是“最简单的”,但简单的理解就可以了:
>>> my_string = "Mary had a little lamb"
>>> sum(char == 'a' for char in my_string)
4
使用计数:
sentence = 'A man walked up to a door'
print(sentence.count('a'))
# 4
我是pandas库的粉丝,特别是value_counts()
方法。您可以使用它来计算字符串中每个字符的出现次数:
>>> import pandas as pd
>>> phrase = "I love the pandas library and its `value_counts()` method"
>>> pd.Series(list(phrase)).value_counts()
8
a 5
e 4
t 4
o 3
n 3
s 3
d 3
l 3
u 2
i 2
r 2
v 2
` 2
h 2
p 1
b 1
I 1
m 1
( 1
y 1
_ 1
) 1
c 1
dtype: int64
count
绝对是在字符串中计算字符出现次数最简洁高效的方法,但我尝试使用lambda
来找到另一种解决方案,就像这样:
sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))
这将导致:
4
in
,这也会给出正确的结果。看一下:sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))
4
获取所有字符计数的另一种方式,不使用Counter()
、count
和正则表达式。
counts_dict = {}
for c in list(sentence):
if c not in counts_dict:
counts_dict[c] = 0
counts_dict[c] += 1
for key, value in counts_dict.items():
print(key, value)
我知道要求是计算特定字母的数量。我在此编写通用代码,不使用任何方法。
sentence1 =" Mary had a little lamb"
count = {}
for i in sentence1:
if i in count:
count[i.lower()] = count[i.lower()] + 1
else:
count[i.lower()] = 1
print(count)
输出
{' ': 5, 'm': 2, 'a': 4, 'r': 1, 'y': 1, 'h': 1, 'd': 1, 'l': 3, 'i': 1, 't': 2, 'e': 1, 'b': 1}
print(count['m'])
2
最简单的方法是在一行代码中编写:
'Mary had a little lamb'.count("a")
sentence ='Mary had a little lamb'
count=0;
for letter in sentence :
if letter=="a":
count+=1
print (count)
a = "I walked today,"
c=['d','e','f']
count=0
for i in a:
if str(i) in c:
count+=1
print(count)
ab = set("Mary had a little lamb")
test_str = "Mary had a little lamb"
for i in ab:
counter = test_str.count(i)
if i == ' ':
i = 'Space'
print(counter, i)
1 : r ,
1 : h ,
1 : e ,
1 : M ,
4 : a ,
1 : b ,
1 : d ,
2 : t ,
3 : l ,
1 : i ,
4 : Space ,
1 : y ,
1 : m ,
''.join()
制造了不必要的方式。 - questionto42set()
,循环遍历以检查集合中每个字母的count()
。它将结果添加到字典的键中,并在之后打印字典,而不是这个答案在循环期间直接打印计数(打印结果的方式不是主要问题)。因此出现了重复。 - questionto42' '
为键,以 ' '
数量为值的字典。你可以使用 pop
将字典的键重命名为任何你喜欢的名称,比如将 ' '
改为 space
,但这并没有增加价值。我仍然撤回我的踩票,因为有人可能想要一个不带字典的解决方案。然而,这是一个重复的问题,主要的技巧只是 set()
和 count()
,你重复了它们。 - questionto42Python 3
有两种方法可以实现这个:
1) 使用内置函数count()
sentence = 'Mary had a little lamb'
print(sentence.count('a'))`
sentence = 'Mary had a little lamb'
count = 0
for i in sentence:
if i == "a":
count = count + 1
print(count)