Python Forum
set and sorted, not working how expected! - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: set and sorted, not working how expected! (/thread-35991.html)



set and sorted, not working how expected! - wtr - Jan-07-2022

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.


RE: set and sorted, not working how expected! - Yoriz - Jan-07-2022

sets are unordered
https://docs.python.org/3/tutorial/datastructures.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.
...



RE: set and sorted, not working how expected! - bowlofred - Jan-07-2022

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))