How to count amount of times partial string appears in list?

Viewed 143

Say I have a list and I want to count how many times a partial string appears "AB" Is there a way to make count() work? I want to try and make this as efficient as possible without breaking the code down into a loop.

my_list = ["ABC", "ABD", "DCF", "ARC", "AVB", "ABG"]

Correct output = 3

5 Answers

What is your expected behavior for ["ABAB"]? Do you want 2 or 1? If you want 2, you will still get value out of "count".

sum(s.count("AB") for s in my_list)

That being said, your problem seems poorly defined, what if your string is "AA", how many do you expect for ["AAA", "AA", "A"]? 1 (exact)? 2 (per item)? 3 (all possible ranges)?

Loop through each element as follows:

sum(1 for i in my_list if "AB" in i)

Or a longer alternative:

count = 0
for i in my_list:
    if "AB" in my_list[i]: count+=1

Note: I know the OP doesn't want to loop but I don't think it's possible without one.

You can use the sum built-in function. In your case,

my_list = ["ABC", "ABD", "DCF", "ARC", "AVB", "ABG"]
sum('AB' in s for s in my_list)

Output: 3

This code works because booleans can be treated as integers. Each time 'AB' appears in a string element, True is returned. The integer value of True is 1. So it's as if each time 'AB' is in a string, 1 is returned. Thus, summing the 1's returned will yield the number of times 1 appeared in an element.

If it's a huge list that hurts time efficiency, you can parallelize this.

  • Initialize a globalCounter
  • Split the list into n chunks
  • For each chunk, spawn a thread and send it to a function that internally runs a loop to count "AB" occurrence in that chunk
  • Let every thread update the globalCounter
  • When all the thread finish execution, return the globalCounter as result

Although this still effectively loops through the entire list, parallelization improves the time.

You can turn it into a string and use str.count:

>>> my_list = ["ABC", "ABD", "DCF", "ARC", "AVB", "ABG"]
>>> ' '.join(my_list).count('AB')
3

Or use sum and a comprehension:

>>> sum(s.count('AB') for s in my_list)
3
Related