0

To find the cumulative count for a list of elements in another list , I can loop through the list for each element of the sublist (via list.count) and sum them up. Is it possible to the same with a more efficient Pythonic way?

Example:

test_list = [1,1,2,2,2,3,3,3,4,5,5,5]
to_be_counted = [1,2]
result = 5 (1 two times, 2 three times)
utengr
  • 3,225
  • 3
  • 29
  • 68
  • why do you want to use `list.count` internal function? Time complexity of the O(n) according to this post [https://stackoverflow.com/a/44813154/5222075]. So over all time complexity O(n*k), where n is number of elements in test_list, k is number of elements in to_be_counted. – Venkatesh Mondi Mar 05 '21 at 12:08
  • 2
    E.g. `len([n for n in test_list if n in to_be_counted])`. – mportes Mar 05 '21 at 12:09

1 Answers1

0

try map and sum:

test_list = [1,1,2,2,2,3,3,3,4,5,5,5]
to_be_counted = [1, 2]
print(sum(map(test_list.count, to_be_counted)))
JacksonPro
  • 3,135
  • 2
  • 6
  • 29