Skip to content Skip to sidebar Skip to footer

How To Print Elements Which Occur Only Once In A List, Without Counting

If I have a dictionary {key : [a b c c d]} and I want to print only the unique values corresponding to each key (In this case, (a,b,d)) what is the most efficient way to do this a

Solution 1:

If elements are sorted as in your example; you could use itertools.groupby():

from itertools import groupby

print " ".join([k for k, groupingroupby(d['key']) iflen(list(group)) == 1])
# -> a b d

Solution 2:

One option, use collections.Counter

from collections import Counter
d = {'k': ['a', 'b', 'c', 'c', 'd']}
c = Counter(d['k'])
print [k for k in c if c[k] == 1]
['a', 'b', 'd']

Solution 3:

You can use Counter from collections:

>>> d = {'key': ['a', 'b', 'c', 'c', 'd']}
>>> >>> from collections import Counter
>>> >>> new_dict = Counter(d['key'])
>>> new_dict
Counter({'c': 2, 'a': 1, 'b': 1, 'd': 1})
>>> [elem for elem in new_dict.keys() if new_dict[elem] == 1]
['a', 'b', 'd']

Solution 4:

Not using a Counter:

unique = []
for i, val in enumerate(d['key']):
    if item not in d['key'][i+1:] and item not in d['key'][:i]:
        unique.append(item)

Using a generator comprehension:

unique = list((d['key'][i] for i in range(len(d['key'])) if d['key'][i] not in d['key'][i+1:] and d['key'][i] not in d['key'][:i]))

Solution 5:

Assuming the list is sorted:

>>>L = [1, 1, 2, 3, 4, 4, 4, 5]>>>[e for i, e inenumerate(L) if e == L[i-1] and i < len(L)-1andnot e == L[i+1]]
[1, 4]

Post a Comment for "How To Print Elements Which Occur Only Once In A List, Without Counting"