Jacques Scheire
Jacques Scheire

Reputation: 21

How do I omit duplicates in a list?

I am currently trying to write a program that counts how many times a word occurs in an input. I am currently running into the following problem:

Take for example this:

list: ['red', 'green', 'blue', 'green']

If I use a for loop like this:

for i in range(len(userinput)):
    list.count(userinput[i])

it would simply return: 1, 2, 1, 2

How would I make it return: 1, 2, 1, counting another occurrence only once?

Upvotes: 1

Views: 53

Answers (5)

Jignesh Jarsaniya
Jignesh Jarsaniya

Reputation: 589

Here is the best way.

userinput = ['red', 'green', 'blue', 'green']
set = set([])
for input in userinput :
    set.add(userinput.count(input))
print set

You get

set([1, 2])

Another Example,

userinput = ['red', 'green', 'blue', 'green', 'green'] #Added green
set = set([])
for input in userinput :
    set.add(userinput.count(input))
print set

you get

set([1, 3])

Try this

Upvotes: 1

Chris
Chris

Reputation: 22953

You can use collections.defaultdict:

>>> from collections import defaultdict
>>> 
>>> def element_count(lst):
    count = defaultdict(int)
    for element in lst:
        count[element] += 1
    return list(count.values())

>>> 
>>> lst = ['red', 'green', 'blue', 'green']
>>> element_count(lst)
[1, 1, 2]
>>> 

Upvotes: 0

Vaishali
Vaishali

Reputation: 38415

I am not sure if just the count in the form [1,2,1] would be of much meaning. Ideally you would need a dictionary with the count of each element like this:

l = ['red', 'green', 'blue', 'green']
from collections import Counter
Counter(l)

You get

Counter({'blue': 1, 'green': 2, 'red': 1})

If you wish to do this without Counter, try

 dict((item, l.count(item)) for item in l)

and you get

{'blue': 1, 'green': 2, 'red': 1}

Upvotes: 3

igor
igor

Reputation: 742

You can use HashTable where the key is the word and the value is a counter. Each time you see the word increase the counter, if it's a new word set the counter to one.

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113940

counts = []
seen = set()
for a_string in userinput_list: 
    if a_string not in seen: 
        print(a_string,"=",userinput_list.count(a_string))
        seen.add(a_string)

I guess ... theres better ways to do this but this should work

Upvotes: 1

Related Questions