6

I have a list of letters and letter clusters, like this:

['x', 'str', 'a', 'pr']

I have a string that I need to know how many total occurrences of any member of the list are in it:

stripe = 1, rope = 0,, rprpraxp = 4, etc

Now I can loop over the members of the list counting occurrences of each member and then total them, like this:

sublist = ['x', 'str', 'a', 'pr']
string = "rprpraxp"
inst = 0
for member in sublist:
    inst = inst + string.count(member)
print(inst)

However I am wondering if I am missing a shorter, simpler, more intuitive and more Pythonic way of counting the members of a set of items in another string, something like:

inst = string.multicount(['x', 'str', 'a', 'pr'])

Anything like this exist?

Thanks.

3
  • Use the package collections -- see the counter object. Commented Nov 3, 2017 at 18:36
  • 2
    What if strings overlap? Example: list is ['ab', 'ba'] and string is 'aba'. Is the answer 1 or 2? Commented Nov 3, 2017 at 18:42
  • I'm coding my text to make sure that does not happen - but good catch! Commented Nov 3, 2017 at 19:52

2 Answers 2

2

I would use map and sum:

sublist = ['x', 'str', 'a', 'pr']
string = "rprpraxp"
print(sum(map(string.count, sublist)))
Sign up to request clarification or add additional context in comments.

4 Comments

Because sets are faster?
Yes, sets have faster lookups than list. You won't notice any difference in this case because it is a small list of strings. I'm just pointing it out. I edited to let it as a list though it is completely trivial in this case.
Just to confirm, what you are calling a set is the same thing as a tuple, right? Or is this a new type I haven't bumped into yet?
Yea Initially I used tuples and it was my mistake. I understand the confusion. here is the way your create both mytuple = (1,2,3) and myset = {1,2,3}. Set can also be initialize like this myset=set(1,2,3)
0
>>> S = "rprpraxp"
>>> L = ['x', 'str', 'a', 'pr']
>>> sum(S.count(e) for e in L if e in S)
4

2 Comments

Won't you get the same answer if you omit if e in S?
@Robᵩ: Sure. Might even be a bit faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.