Python Forum

Full Version: set and sorted, not working how expected!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello all,

I implemented the following. I don't understand why the output is unsorted list. I'm using set and sort to filter my list.
freq_list = set(sorted(i.f_center for i in ret))

However breaking down the steps
  1. i.f_center for i in ret # extracts a list of frequency values. See below
a = [1225000000.0, 5800000000.0, 434000000.0, 2450000000.0, 2425000000.0, 5750000000.0, 455000000.0, 441000000.0, 441000000.0, 5850000000.0, 455000000.0, 1225000000.0, 5740000000.0, 5800000000.0, 1200000000.0, 5820000000.0, 441000000.0, 2475000000.0, 5850000000.0, 915000000.0, 2585000000.0, 5740000000.0, 2425000000.0, 5750000000.0, 1165000000.0, 1225000000.0, 915000000.0, 434000000.0, 872000000.0, 5800000000.0, 2415000000.0, 2415000000.0, 2425000000.0, 1105000000.0, 872000000.0, 5750000000.0, 434000000.0, 2450000000.0, 2475000000.0, 455000000.0, 1255000000.0, 1105000000.0, 1255000000.0, 2585000000.0, 5870000000.0, 915000000.0, 2585000000.0, 1165000000.0, 2450000000.0, 5820000000.0, 5870000000.0, 5740000000.0, 5870000000.0, 5820000000.0, 5780000000.0, 2475000000.0, 2415000000.0, 1105000000.0, 5850000000.0, 1200000000.0, 5780000000.0, 1200000000.0, 1165000000.0, 5780000000.0, 872000000.0, 1255000000.0]
[list=2]
[*]now apply the sorted and set functions.
[/list]
a1 = sorted(a)
print(a1)
a2 = set(a1)
print(a2)
You'll notice that 441000000.0, is not where I expect it.
sets are unordered
https://docs.python.org/3/tutorial/datas....html#sets Wrote:Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
...
Do it in the other order. Create a set from them if you want to remove duplicates, then sort it (into a list) if you want a particular order.

a2 = sorted(set(a))