Reputation: 22094
The return value of sort() is None so the following code doesn't work:
def sorted_unique_items(a):
return list(set(a)).sort()
Any idea for better solution?
Upvotes: 2
Views: 1184
Reputation: 1204
There is Two options:
a = [2,34,55,1,22,11,22,55,1]
#First option using sorted and set.
sorted(set(a))
#second option using list and set.
list(set(a))
Upvotes: -1
Reputation: 980
Above solution is only work for hashable type like string,integer and tuple but it not work for unhashable type like list.
for example if you have a list data= [[2],[1],[2],[4]]
for unhashable type best solution is :
from itertools import izip, islice
values= [[2],[1],[2],[4]]
def sort_unique_unhashable(values):
values = sorted(values)
if not values:
return []
consecutive_pairs = izip(values, islice(values, 1, len(values)))
result = [a for (a, b) in consecutive_pairs if a != b]
result.append(values[-1])
return result
print sort_unique_unhashable(values)
Upvotes: 0
Reputation: 1204
Its simple Just use the sorted()
method :
data = [10,5,46,4]
sorted_data = sorted(data)
print "Sorted Data ::::",sorted_data
Upvotes: 1
Reputation: 1123410
Use sorted()
:
sorted(set(a))
and you can omit the list()
call entirely.
Upvotes: 6