Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python to find objects in array with same starting characters

Tags:

python

I'm new to python and would like to know if there is an easy way to search for Strings in array that have the same starting characters.

for example I have a list

ex = [exA, exB, teA, exC]

and want to get result for everything matching the first two characters something like this:
{'ex' : 3, 'te' : 1}

I have tried working with the Counter method from collections but I cant get a result as shown above.

thank you in advanced

like image 413
Alex.JvV Avatar asked Jan 03 '23 13:01

Alex.JvV


1 Answers

If you slice off the first two characters of each element you can use collections.Counter for this

>>> import collections
>>> ex = ['exA', 'exB', 'teA', 'exC']
>>> collections.Counter(i[:2] for i in ex)
Counter({'ex': 3, 'te': 1})
like image 53
Cory Kramer Avatar answered Feb 01 '23 13:02

Cory Kramer