如何让Julia的Permutations包返回常规整数数组?
解决Julia Permutations包逆排列结果类型问题
我来帮你搞定这个类型转换的问题!你现在得到LinearAlgebra.Adjoint类型,是因为代码里连续用了两次转置操作(.'和'),生成的是原数组的视图而非独立的二维整数数组。咱们可以换更直观的方式生成逆排列,同时直接得到标准的3×4整数数组:
方法一:使用Permutation的inv()方法(推荐)
Permutation对象本身提供了inv()方法来直接获取逆排列,比转置操作更贴合语义,还能避免Adjoint类型的问题:
using Permutations # 先把students写成更清晰的二维数组形式(原写法也可以,但分号分隔行更直观) students = [3 4 2 1; 3 4 1 2; 4 3 2 1] # 生成逆排列数组 students_inv = stack([inv(Permutation(row)).data for row in eachrow(students)]; dims=1)
inv(Permutation(row)):直接对每行生成的Permutation对象取逆.data:提取逆排列内部的一维整数数组stack(..., dims=1):把多个一维数组按行堆叠成二维数组(Julia 1.9及以上版本支持,非常简洁)
如果你用的是旧版Julia,也可以用hcat+转置的方式:
students_inv = hcat([inv(Permutation(row)).data for row in eachrow(students)]...)'
方法二:修复原有代码,转换Adjoint为普通数组
如果你不想改动核心逻辑,也可以把生成的Adjoint视图转换成普通数组,再组合成二维数组:
students_inv = [collect(Permutation(i)'.data') for i in eachrow(students)] # 把一维数组列表转换成二维数组 students_inv = vcat(students_inv...)
验证结果
执行后students_inv会是标准的3×4 Array{Int64,2},完全符合你的需求:
3×4 Matrix{Int64}: 4 3 1 2 3 4 1 2 4 3 2 1
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

