如何根据其中一个值有效地对两个数组进行分类?

发布于 2025-02-06 23:07:53 字数 250 浏览 1 评论 0 原文

如果我有两个数组:

a = [  1,   4,   3,   2]
b = ['z', 'w', 'x', 'y']

值对 a a b 进行排序。

[  1,  2,  3,  4]      # a 
['z','y','x','w']      # b

并且我想根据 a 的 惯用方式做到这一点?

If I have two arrays:

a = [  1,   4,   3,   2]
b = ['z', 'w', 'x', 'y']

and I want to sort both a and b based on the values from a, i.e.:

[  1,  2,  3,  4]      # a 
['z','y','x','w']      # b

What is an efficient/idiomatic way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉城凉梦凉人心 2025-02-13 23:07:53

对于两个不同的向量,我不知道这是否可能。

我将使用 sortperm 返回一个返回置换式vector > p a [p] 放置顺序排序的顺序,

julia> p=sortperm(a)
4-element Vector{Int64}:
 1
 4
 3
 2

julia> a[p]
4-element Vector{Int64}:
 1
 2
 3
 4

julia> b[p]
4-element Vector{Char}:
 'z': ASCII/Unicode U+007A (category Ll: Letter, lowercase)
 'y': ASCII/Unicode U+0079 (category Ll: Letter, lowercase)
 'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
 'w': ASCII/Unicode U+0077 (category Ll: Letter, lowercase)

如果性能很重要,您还可以使用 sortperm!,允许使用preallocated置换置换量向量 p


注意:如果您有矩阵,则可以使用分类

julia> M=hcat(a,b)
4×2 Matrix{Any}:
 1  'z'
 4  'w'
 3  'x'
 2  'y'

julia> sortslices(M,dims=1,by=x->x[1])
4×2 Matrix{Any}:
 1  'z'
 2  'y'
 3  'x'
 4  'w'

With two distinct vectors I do not know if this is possible.

I would use sortperm that returns a permutation vector p that puts a[p] in sorted order

julia> p=sortperm(a)
4-element Vector{Int64}:
 1
 4
 3
 2

julia> a[p]
4-element Vector{Int64}:
 1
 2
 3
 4

julia> b[p]
4-element Vector{Char}:
 'z': ASCII/Unicode U+007A (category Ll: Letter, lowercase)
 'y': ASCII/Unicode U+0079 (category Ll: Letter, lowercase)
 'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
 'w': ASCII/Unicode U+0077 (category Ll: Letter, lowercase)

If performance is important you can also use sortperm! that allows using a preallocated permutation vector p.


Note: if you have a matrix you can use sortslices

julia> M=hcat(a,b)
4×2 Matrix{Any}:
 1  'z'
 4  'w'
 3  'x'
 2  'y'

julia> sortslices(M,dims=1,by=x->x[1])
4×2 Matrix{Any}:
 1  'z'
 2  'y'
 3  'x'
 4  'w'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文