Reputation: 743
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
Upvotes: 0
Views: 503
Reputation: 873
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))
Upvotes: 3