How To Count Numbers In A List Via Certain Rules?
Just to say I have a str and a list of strs and I want to count how many strs in the list that is contained in a str. Is there an elegant way to do that? For example, l = {'foo',
Solution 1:
sum(s in my_string for s in l)
Solution 2:
Here is a simple example,
l = ["foo", "bar", "what"]
st = "foobar"
count = 0
for _string in l:
if _string in st:
count += 1
print(count)
Solution 3:
Use count:
l = {"foo", "bar", "what"}
str = "foobar"c = [item in str for item in l].count(True)
In my opinion this is the most readable version. item in str
means check if item
is a substring of str
. for item in l
means that it should iterate through each list item in l
(btw convention is not to use lowercase L for a variable name, as it looks nearly identical to the numeral 1 in many fonts). Finally .count(True)
returns the number of times True
exists in the list.
Solution 4:
Yet another solution
count = sum(item in str for item in l)
Post a Comment for "How To Count Numbers In A List Via Certain Rules?"