在 python 中用一个 while 和一个 for 循环计算字符串中某个字符有多少

Counting how many of a certain character there are in a string with one while and one for loop in python

我得到了一个带有随机字符串的问题,例如

example = ‘asdkfkebansmvajandnrnndklqjjsustjwnwn’

并被要求用 while 和 for 循环找出这个字符串中 a 的个数

因此不允许像这样简单地使用 count() 函数:

print('# of a:’, example.count(‘a’))

我们得到了一个例子:(并被告知要找到不同的方法)

counter = 0
for letter in example:
   if letter == ‘a’:
        counter = counter + 1
print(counter)

我对python很陌生,实在找不到办法。我想将这个字符串转换成一个列表,其中包含每个字符作为不同的对象,如下所示:

example_list = list(example)

可是后来还是找不到办法

我们有两个起点,所以结束代码的格式必须有点相似,我们实际上不允许使用更高级的函数(到目前为止,允许使用简单的字符串或列表函数和 if 语句据我所知)。

对于 while 循环:

counter = 0
while counter < 4:
    print(example_list[counter])
    counter += 1

for 循环:

for counter in range(0, len(example_list)):
    print(counter, example[counter])

我要么打印每个字符及其位置,要么打印数字而不实际使用循环。

我认为这些建议告诉您必须使用计数器遍历数组。 这是 while 循环的示例:

example = 'asdkfkebansmvajandnrnndklqjjsustjwnwn'
counter = 0
a_count = 0
while counter < len(example):
    if example[counter] == 'a':
        a_count += 1
    counter += 1
print(a_count)

for 循环可能如下所示:

for counter in range(len(example)):
    if example[counter] == 'a':
        a_count += 1

请注意,转换为列表不是必需的,因为您可以使用与遍历已转换为列表的字符串完全相同的方式来遍历字符串。

对于你的第一个起点,我认为这个想法是按索引迭代:

index = 0
counter = 0
while index < len(example):
    if example[index] == 'a':
        counter += 1
    index += 1

for 循环版本为:

counter = 0
for index in range(len(example)):
    if example[index] == 'a':
        counter += 1

注意:像这样按索引迭代实际上在 Python 中被认为是不好的做法(因为它基本上只是添加不必要的工作),并且首选方法是按值迭代,如在给定的示例中然后告诉不要用。

两个函数,while_countfor_count,实现你所需要的:

def while_count(s):
    counter, i = 0, 0
    while i < len(s):
        if s[i] == "a":
            counter += 1
        i += 1
    return counter


def for_count(s):
    counter = 0
    for i in range(len(s)):
        if s[i] == "a":
            counter += 1
    return counter

您可以使用列表理解使 for 案例变得更简单:

def for_count2(s):
    return sum([x=="a" for x in s])

这是您问题的解决方案

1.Using 循环

example = 'asdkfkebansmvajandnrnndklqjjsustjwnwn'
count=0
for i in example:
    if i.lower()=='a':
        count+=1
print(count)

2。使用 While 循环:

example = 'asdkfkebansmvajandnrnndklqjjsustjwnwn'
loop_count=0
a_counter=0
lis=list(example)
while loop_count<len(example):
    if lis[loop_count]=='a':
        a_counter+=1
    loop_count+=1
print(a_counter)

如果它投票支持我的答案可能会有帮助