【问题标题】:Sorting matrix columns [closed]排序矩阵列[关闭]
【发布时间】:2023-01-27 00:33:28
【问题描述】:

我有一个 4*5 矩阵,我需要按几列对它进行排序。请帮我弄清楚为什么答案不匹配。

我花了很多时间,也许是一个愚蠢的错误。如果您能指出给我,我将不胜感激。

sort_columns = [3, 1, 2, 4, 5, 2]
matrix = [[3, 1, 8, 1, 9],
          [3, 7, 8, 2, 9],
          [2, 7, 7, 1, 2],
          [2, 1, 7, 1, 9]]
sort_matrix_columns(matrix, len(matrix), sort_columns)
def sort_matrix_columns(matrix, n, sort_columns):
    for col in sort_columns:
        column = col - 1
        for i in range(n):
            for j in range(i + 1, n):
                if matrix[i][column] > matrix[j][column]:
                    temp = matrix[i]
                    matrix[i] = matrix[j]
                    matrix[j] = temp

我希望得到结果:

2 1 7 1 9
3 1 8 1 9
2 7 7 1 2
3 7 8 2 9

但我得到以下信息:

3 1 8 1 9 
2 1 7 1 9 
2 7 7 1 2 
3 7 8 2 9 

【问题讨论】:

  • 你好 Tivasic,欢迎来到 StackOverflow。不幸的是,我不明白你想如何对矩阵进行排序,因为你的“预期结果”对我来说并没有排序。你能扩展你正在尝试做的事情吗?
  • @FlorianFasmeyer,你好!我按列中的项目排序。如果 1 列中的元素小于 2 列中的元素,则行会发生变化,依此类推。
  • @FlorianFasmeyer。在我的例子中,我首先查看位置 3 中的元素(基于 sort_columns 列表)。然后我遍历所有行,位置 3 有必要增加。

标签: python sorting matrix


【解决方案1】:

您可以只使用默认的sorted() 函数,并为其提供一个键来检索列值,此时通过直接比较键值对行进行排序。

key 是可调用的(就像一个函数),它被赋予每个正在排序的项目,并且您需要返回一个正在比较的值。

在您的情况下,只需映射列号,相反:

def sort_matrix_columns(matrix, n, sort_columns):
    return sorted(
        matrix,
        key=lambda row: [row[col - 1] for col in sort_columns[::-1]]
    )

请注意,可以删除函数的 n 参数,不使用它。

演示:

>>> sort_columns = [3, 1, 2, 4, 5, 2]
>>> matrix = [[3, 1, 8, 1, 9],
...           [3, 7, 8, 2, 9],
...           [2, 7, 7, 1, 2],
...           [2, 1, 7, 1, 9]]
>>> sorted(matrix, key=lambda row: [row[col - 1] for col in sort_columns[::-1]])
[[2, 1, 7, 1, 9], [3, 1, 8, 1, 9], [2, 7, 7, 1, 2], [3, 7, 8, 2, 9]]

您的实施失败,因为您正在对元素进行排序到位,因此将根据已经换出的行做出交换决定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-02
    • 2022-08-17
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2022-12-22
    相关资源
    最近更新 更多