Reputation: 13
Looking for the best way of doing this:
So i have a list containing unicode strings, lets call this listA
I have a list of tuples, each of the tuples contains a unicode string and an integer, lets call this listB
What i need to do is to find each of the strings in listA in listB's tuples. If its found then increment the integer in that tuple.
I can think of long ways to do this by creating a new list of tuples, but i'm not convinced this is the best way.
Any assistance gratefully received
Upvotes: 1
Views: 79
Reputation: 6387
Use collections.Counter, you'll get result as dictionary:
from collections import Counter
txt = """Looking for the best way of doing this:
So i have a list containing unicode strings, lets call this listA I
have a list of tuples, each of the tuples contains a unicoe string
and an integer...
""".split() # this gives list of words
counter = Counter(txt)
for word, count in counter.items():
print "{}: {}".format(word, count)
In fact counter.items()
gives you tuples you need.
Counter gives you much more, try stuff like counter.most_common()[:10]
and have fun.
[edit] of course later you can increment values with counter.update(another_list_of_words)
.
Upvotes: 0
Reputation: 250891
You should use collections.Counter
for this:
>>> from collections import Counter
>>> listA = ['a', 'b', 'c', 'a', 'c']
>>> listB = [('a', 5), ('b', 10), ('c', 0)]
Convert listB
to a Counter
object first:
>>> c = Counter(dict(listB))
>>> c
Counter({'b': 10, 'a': 5, 'c': 0})
Now update it with the count from listA
:
>>> c.update(listA)
>>> c
Counter({'b': 11, 'a': 7, 'c': 2})
Upvotes: 3