0

I have a list present with some elements stored . I want to apply ssome function on all elements of the list and want to sort the list into reverse order.Then I would like to convert the resulting list to set(). But my code does not seem to work. Can somebody take a look and tell me what is wrong with my code. The last line is the output from print a. What is wrong with this code

B=[2,3,4,5,7,66,56,34,22,345, 22,3,5]
a=set(sorted([2*t for t in B], reverse=True))
print(a)
# output: {132, 68, 6, 4, 8, 10, 44, 14, 112, 690}

Now in other form , my code is :

sorted(set([2*t for t in B]), reverse=True)

which seems to work out fine and produce:

[690, 132, 112, 68, 44, 14, 10, 8, 6, 4]

can somebody tell the difference

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149

1 Answers1

0

Set objects don't preserve the order because they use hashtable for preserving their items. Instead you can use OrderedDict.fromkeys to get unique and ordered representation of an iterable.

In [6]: sorted_b = sorted([2*t for t in B], reverse=True)

In [7]: from collections import OrderedDict

In [8]: OrderedDict.fromkeys(sorted_b)
Out[8]: 
OrderedDict([(690, None),
             (132, None),
             (112, None),
             (68, None),
             (44, None),
             (14, None),
             (10, None),
             (8, None),
             (6, None),
             (4, None)])
Mazdak
  • 105,000
  • 18
  • 159
  • 188