You can do this by using the sum built-in function. No need to use list.count as well: >>> data = ["the foo is all fooed", "the bar is all barred", "foo is now a bar"] >>> sum('foo' in s for s in data) 2 >>>This code works because booleans can be treated as integers. Each time 'foo' appears in a string element, True is returned. the integer value of True is 1. So it's as if each time 'foo' is in a string, we return 1. Thus, summing the 1's returned will yield the number of times 1 appeared in an element. A perhaps more explicit but equivalent way to write the above code would be: >>> sum(1 for s in data if 'foo' in s) 2 >>> (责任编辑:) |