gpt4 book ai didi

python - Python中根据特定顺序排列括号中的数据

转载 作者:行者123 更新时间:2023-12-01 00:01:37 25 4
gpt4 key购买 nike

我有一个数组,编程后,我得到非零数据的位置和值,看起来像 (x, y, z) = (行, 列, 值)

[(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]

结果按“最小行数到最高行数”的顺序排列。

有什么方法可以使结果按“列数最小到最高”和“值的最小数到最高”顺序排列吗?

感谢您的帮助!!

这是我使用的代码:

import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])
i = np.nonzero(groupMatrix)

res = np.vstack([i, groupMatrix[i]])
print(list(zip(*res)))

最佳答案

你当然可以做到,
在这种情况下,您可以按 key(即

)对 元组列表进行排序
import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])
i = np.nonzero(groupMatrix)

res = np.vstack([i, groupMatrix[i]])
arr = list(zip(*res))

col_sorted = sorted(arr, key=lambda item: item[1]) # sorted by column
val_sorted = sorted(arr, key=lambda item: item[2]) # sorted by value

希望对你有帮助!

关于python - Python中根据特定顺序排列括号中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60312823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com