Using python to search for objects in an array with the same initial characters

I am new to python and would like to know if there is an easy way to search for strings in an array with the same start characters.

for example i have a list

ex = [exA, exB, teA, exC]

and you want to get the result for all that match the first two characters of something like this:
 {'ex': 3, 'te': 1}

I tried to work with the Counter method from collections, but I can not get the result as shown above.

Thank you for advanced

+4
source share
1 answer

If you cut the first two characters of each element, you can use collections.Counterfor this purpose

>>> import collections
>>> ex = ['exA', 'exB', 'teA', 'exC']
>>> collections.Counter(i[:2] for i in ex)
Counter({'ex': 3, 'te': 1})
+9
source

Source: https://habr.com/ru/post/1684230/


All Articles