Unique Elements in a List
Steven Bethard
steven.bethard at gmail.com
Tue May 10 16:04:18 EDT 2005
superprad at gmail.com wrote:
> Is there an easy way to grab the Unique elements from a list?
> For Example:
> data = [0.1,0.5,0.6,0.4,0.1,0.5,0.6,0.9]
>
> what I am looking for is the unique elements 0.4 and 0.9 with their
> index from the list.
This is basically the same as Fredrik Lundh's solution, but here it is
anyway:
py> def f(lst):
... counts = dicttools.counts(lst)
... return [(i, elem)
... for i, elem in enumerate(lst)
... if counts[elem] == 1]
...
py> f([0.1,0.5,0.6,0.4,0.1,0.5,0.6,0.9])
[(3, 0.40000000000000002), (7, 0.90000000000000002)]
Where dicttools.counts is defined as:
def counts(iterable, key=None):
result = {}
for item in iterable:
# apply key function if necessary
if key is None:
k = item
else:
k = key(item)
# increment key's count
try:
result[k] += 1
except KeyError:
result[k] = 1
return result
(I use this so often that I have a module called dicttools to hold it.
You don't actually need the key= argument for your problem, but I just
copied the code directly.)
STeVe
More information about the Python-list
mailing list