search substring in list in python

谁说胖子不能爱 提交于 2020-01-24 01:06:06

问题


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

My code:

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"

回答1:


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"

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

Or as a list comprehension:

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



回答2:


So the question is why doesn't this work?

Your list contains one big string, "apple, banana, Baboon, Charlie".

Add in the single quotes between elements.




回答3:


Based on your latest comment, the code could be rewritten as:

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

You basically join all the strings in the list and make a single long string, then lowercase it (since you don't care about case) and search for lowercase(b). The test on count_total works, because it evals to True if not zero.




回答4:


The generator expression (element.lower().count('b') for element in List1) produces the length for each element. Pass it to sum() to add them up.

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))

Output:

b occurs 3 times

If you want the count for each individual element in the list, use a list comprehension instead. You can then print this list or pass it to 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))

Output:

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


来源:https://stackoverflow.com/questions/34802435/search-substring-in-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!