0

Please help me that how can I sort this List by first element?

List = ([-180.0; -67.5], 0), ([270.0; -570.0], 0), ([180.0, -510.0], 1), ([27.15, -288.75], 1), ([-36.0, -244.5], 1)

sortList = ([-180.0; -67.5], 0), ([-36.0, -244.5], 1), ([27.15, -288.75], 1), ([180.0, -510.0], 1), ([270.0; -570.0], 0)  

Thanks

phipsgabler
  • 20,535
  • 4
  • 40
  • 60
Soma
  • 743
  • 6
  • 19

1 Answers1

3

You cannot sort the "List" because it is not a list in Julia

It is a tuple of tuples.

   $ julia
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.0.3 (2018-12-18)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

   julia> List=([-180.0; -67.5], 0),([270.0; -570.0], 0),([180.0, -510.0], 1),([27.15, -288.75], 1), ([-36.0, -244.5], 1)
(([-180.0, -67.5], 0), ([270.0, -570.0], 0), ([180.0, -510.0], 1), ([27.15, -288.75], 1), ([-36.0, -244.5], 1))

   julia> List
   (([-180.0, -67.5], 0), ([270.0, -570.0], 0), ([180.0, -510.0], 1), ([27.15, -288.75], 1), ([-36.0, -244.5], 1))

   julia> typeof(List)
   NTuple{5,Tuple{Array{Float64,1},Int64}}

It says quite clearly that

Julia has a built-in data structure called a tuple that is closely related to function arguments and return values. A tuple is a fixed-length container that can hold any values, but cannot be modified (it is immutable).

julia> mytuple=([-180.0; -67.5], 0),([270.0; -570.0], 0),([180.0, -510.0], 1),([27.15, -288.75], 1), ([-36.0, -244.5], 1)
(([-180.0, -67.5], 0), ([270.0, -570.0], 0), ([180.0, -510.0], 1), ([27.15, -288.75], 1), ([-36.0, -244.5], 1))

julia> array = [item for item in mytuple]
5-element Array{Tuple{Array{Float64,1},Int64},1}:
([-180.0, -67.5], 0) 
([270.0, -570.0], 0) 
([180.0, -510.0], 1) 
([27.15, -288.75], 1)
([-36.0, -244.5], 1) 

julia> sortedarray = sort(array,by=x -> x[1][1])
5-element Array{Tuple{Array{Float64,1},Int64},1}:
 ([-180.0, -67.5], 0) 
 ([-36.0, -244.5], 1) 
 ([27.15, -288.75], 1)
 ([180.0, -510.0], 1) 
 ([270.0, -570.0], 0) 

julia> resulttuple = tuple( sortedarray... )
(([-180.0, -67.5], 0), ([-36.0, -244.5], 1), ([27.15, -288.75], 1), ([180.0, -510.0], 1), ([270.0, -570.0], 0))
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Steven Siew
  • 843
  • 8
  • 11
  • Actually Julia performs lexicographic sorting by default, so in this case, as you want to sort on the first item that is unique, it is enough to write `Tuple(sort!(collect(mytuple)))`. If you could have duplicates then the approach proposed by Steven is needed `Tuple(sort!(collect(mytuple), by=x->x[1][1]))` (otherwise the sort could be unstable or fail depending on what other elements your data structure would hold). – Bogumił Kamiński Dec 29 '18 at 19:34