Вопрос

Suppose I have a list: ['cat dog', 'cat cat', 'dog', 'cat cat cat']

I want the count for 'cat' to be 3 (unique per item in the list, not 6).

I'm currently using:

counts = [cat dog, cat cat, dog, cat cat cat]
for sentence in sequence_of_sentences:
    counts.update(word for word in sentence.split())

Updated: Should be 3 instances of cat :)

Это было полезно?

Решение 2

Check out collections.Counter and set. Counter is very handy for creating tallies (aka. counting) and set is great for removing duplicates from a sequence.

from collections import Counter

phrases = ['cat dog', 'cat cat', 'dog', 'cat cat cat']    
all_counts = Counter()
occurrence_counts = Counter()

for phrase in phrases:
    words = phrase.split()
    distinct_words = set(words)
    all_counts.update(words)
    occurrence_counts.update(distinct_words)

all_counts['cat']        # 6
occurrence_counts['cat'] # 3

update() updates the tallies based on what you pass it.

Play around with set a bit by running python from from command line and you should get an idea for what is going on above:

$ python
>>> animals = [ 'bird', 'bird', 'cat' ]
>>> set(animals)
set(['bird', 'cat'])
>>> list(set(animals))
['bird', 'cat']

Другие советы

I do not understand how you get 4. Your example list

>>>l=['cat dog', 'cat cat', 'dog', 'cat cat cat']

has 3 unique 'cat''s. First, Second and Last element. In case you want that, use

>>>sum(1 for i in l if 'cat' in i)

or as @holden excellently suggests (it would have never occurred to me)

>>>sum(('cat' in i) for i in l)

which reads excellently.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top