为什么它不打印正确的a数?

2024-10-03 21:28:55 发布

您现在位置:Python中文网/ 问答频道 /正文

list =["jojo","gardan","giga"]

number_of_a = 0

for item in list:

    if "a" in item:

        number_of_a += 1
        print("there is "+str(number_of_a)+ " a's in "+ item)
    else :
        print("sorry")

Tags: ofinnumberforifisitemelse
3条回答

您只是检查每个字符串中是否存在a,而不是检查其中有多少个字符串^如果字符串中有字母“a”,则{}将返回True,否则返回False。然后在计数器上加1

因此,这里第一个字符串将返回False,变量将保持为0,但第二个字符串将其更改为1,最后一个字符串将其更改为2。如果要计算每个字符串中“a”的数量,需要确保为每个字符串重新设置计数器的值,然后需要实际计算“a”的数量,例如迭代所有字符或使用其他人建议的count

list_ =["jojo","gardan","giga"]

for item in list_:
    number_of_a = 0
    for i in item:
        if i == 'a':
            number_of_a += 1
        else:
            continue
        
    if number_of_a:
        print("there is "+str(number_of_a)+ " a's in "+ item)
    else :
        print("sorry")

我假设您想知道列表中每个元素中有多少个“a”。这是代码

l = ["jojo", "gardan", "giga"]
number_of_a = 0

for item in l:
    if "a" in item:
        number_of_a += 1
        print("there is " + str(number_of_a) + " a's in " + item)
    else:
        print("sorry")

输出: 很抱歉 加尔丹有1个a giga中有2个a

所以根据我的理解,你想要计算字符串中字母的出现次数

在python中,最简单的方法是使用count方法,如下所示:

for word in list:
  number_of_a += word.count("a")
  

相关问题 更多 >