【发布时间】:2022-01-28 06:42:18
【问题描述】:
我正在尝试在 Python 中对具有双索引的多元组进行排序。我想按它的第二个索引对其进行排序。元组输出,即“print(max_values)”的输出,如下所示:
(array([[4.15498641]]), 1)
(array([[2.31940546]]), 4)
(array([[0.96185454]]), 8)
(array([[1.29915758]]), 11)
(array([[1.66805024]]), 5)
(array([[1.25312376]]), 13)
(array([[1.81367542]]), 7)
(array([[3.16895748]]), 14)
(array([[3.74632224]]), 0)
(array([[4.87073571]]), 10)
(array([[1.8860763]]), 12)
(array([[1.25379793]]), 6)
(array([[0.60556452]]), 15)
(array([[3.09510515]]), 3)
(array([[2.7700944]]), 9)
(array([[2.65579492]]), 2)
我真正想做的是,就是按照你看到的元组的第二个索引,把这些元组按顺序排列。
例如,在我添加的输出中,第一个元组的第二个索引是 1,而第二个元组的第二个索引是 4。我要做的是设置第二个索引等于 2。
我也在添加完整代码,“takeSecond”功能不起作用。
import numpy as np
import random
random.seed(2)
np.random.seed(2)
x_train = [(np.random.randn(1,3),0), (np.random.randn(1,3),1), (np.random.randn(1,3),2) , (np.random.randn(1,3),3),
(np.random.randn(1,3),4), (np.random.randn(1,3),5), (np.random.randn(1,3),6) , (np.random.randn(1,3),7),
(np.random.randn(1,3),8), (np.random.randn(1,3),9), (np.random.randn(1,3),10), (np.random.randn(1,3),11),
(np.random.randn(1,3),12),(np.random.randn(1,3),13),(np.random.randn(1,3),14), (np.random.randn(1,3),15)]
neurons = [(np.random.randn(3,1),0), (np.random.randn(3,1),1), (np.random.randn(3,1),2),
(np.random.randn(3,1),3), (np.random.randn(3,1),4), (np.random.randn(3,1),5),
(np.random.randn(3,1),6), (np.random.randn(3,1),7), (np.random.randn(3,1),8)]
def takeSecond(elem):
return elem[1]
#%%
random.shuffle(x_train)
for i in range (len(x_train)):
results = []
winning_neurons = []
for j in range (len(neurons)):
result = np.dot(x_train[i][0],neurons[j][0])
results.append((result,x_train[i][1]))
#results.sort(key=takeSecond)
#print(results)
max_values = max(results)
print(max_values)
max_index = results.index(max_values)
winning_neurons.append(max_index)
#print(winning_neurons)
互联网上的其他元组排序功能,不起作用并给出诸如“索引错误”或“sort() 函数不适用于元组”之类的错误。
你能帮我整理一下吗?提前谢谢你。
【问题讨论】:
-
您能否将
results.sort调用未注释时得到的确切错误包括在内? -
“元组输出”的性质尚不清楚。是连续打印吗?从哪里来的代码?您是否尝试对此类元组的列表进行排序?要获得最佳答案,请让示例和代码简单且可重现,并完整显示任何错误。
-
@shriakhilc 你好,我在代码中编写并注释的“result.sort”调用没有给出错误,但它不能按我的意愿工作。不对元组进行排序。我为我的问题添加了新的解释。你可以看看。
-
@hpaulj 你好,我添加了新的解释。你可以看看。元组输出是“max_values”的输出。但我无法按第二个索引排序。
-
@Manlai 你好,我没有得到编译器的错误声明,但正如我所说,元组不是按它们的第二个索引排序的。
标签: python numpy sorting tuples