【问题标题】:search substring in list in python在python中的列表中搜索子字符串
【发布时间】:2016-04-20 12:53:46
【问题描述】:

我需要知道字母 b(最好是大写和小写)是否包含在一个列表中。

我的代码:

List1=['apple', 'banana', 'Baboon', 'Charlie']
if 'b' in List1 or 'B' in List1:
    count_low = List1.count('b')
    count_high = List1.count('B')
    count_total = count_low + count_high   
    print "The letter b appears:", count_total, "times."
else:
    print "it did not work"

【问题讨论】:

    标签: python list search substring


    【解决方案1】:

    您需要遍历您的列表并遍历每个项目,如下所示:

    mycount = 0
    for item in List1:
        mycount = mycount + item.lower().count('b')
    
    if mycount == 0:
        print "It did not work"
    else:
        print "The letter b appears:", mycount, "times"
    

    您的代码不起作用,因为您试图在列表中计算 'b' 而不是每个字符串。

    或者作为列表理解:

    mycount = sum(item.lower().count('b') for item in List1)
    

    【讨论】:

    • 为了同时考虑大写/小写,我将 mycount 语句更改为使用 item.lower().count('b')
    • 谢谢。有没有办法在列表中搜索而不在每个字符串中搜索?
    • mycount = "".join(List1).lower().count('b')
    • @Robo 上面说的萨尔是什么^。我的解决方案只是一个很好且易于理解的解决方案:)
    • 我只是想补充一点,您的解决方案也适用于在其他列表(如元组)中搜索列表中的字符。那是我真正需要的,再次感谢!
    【解决方案2】:

    所以问题是为什么这不起作用?

    您的列表包含一个大字符串,“apple,banana, Baboon, Charlie”。

    在元素之间添加单引号。

    【讨论】:

    • 我进行了编辑,使列表现在包含多个键。初学者错误:)。但是还是不行。
    【解决方案3】:

    根据您的最新评论,代码可以改写为:

    count_total="".join(List1).lower().count('b')
    if count_total:
       print "The letter b appears:", count_total, "times."
    else:
       print "it did not work"
    

    您基本上连接列表中的所有字符串并创建一个长字符串,然后将其小写(因为您不关心大小写)并搜索小写(b)。对 count_total 的测试有效,因为如果不为零,它的值为 True。

    【讨论】:

    • 运行良好且易于理解。谢谢你。
    【解决方案4】:

    生成器表达式(element.lower().count('b') for element in List1) 生成每个元素的长度。将其传递给sum() 以将它们相加。

    List1 = ['apple', 'banana', 'Baboon', 'Charlie']
    num_times = sum(element.lower().count('b')
                    for element in List1)
    time_plural = "time" if num_times == 1 else "times"
    print("b occurs %d %s"
          % (num_times, time_plural))
    

    输出:

    b occurs 3 times
    

    如果您想要列表中每个单独元素的计数,请改用列表推导式。然后你可以print这个列表或将它传递给sum()

    List1 = ['apple', 'banana', 'Baboon', 'Charlie']
    num_times = [element.lower().count('b')
                 for element in List1]
    print("Occurrences of b:")
    print(num_times)
    print("Total: %s" % sum(b))
    

    输出:

    Occurrences of b:
    [0, 1, 2, 0]
    Total: 3
    

    【讨论】:

      猜你喜欢
      • 2016-04-21
      • 2020-03-12
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多