[英]search substring in list in python
我需要知道字母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"
您需要遍歷列表並遍歷所有項目,如下所示:
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)
所以問題是為什么這不起作用?
您的列表包含一個大字符串,“蘋果,香蕉,狒狒,查理”。
在元素之間添加單引號。
根據您的最新評論,該代碼可以重寫為:
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。
生成器表達式(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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.