在python列表中搜索子字符串 [英] search substring in list in python

查看:114
本文介绍了在python列表中搜索子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道字母b(最好是大写还是小写)是否包含在列表中.

I need to know if the letter b (both uppercase and lowercase preferably) consist in a list.

我的代码:

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"

推荐答案

您需要遍历列表并遍历所有项目,例如:

You need to loop through your list and go through every item, like so:

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'.

Your code doesn't work since you're trying to count 'b' in the list instead of each string.

或作为列表理解:

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

这篇关于在python列表中搜索子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆