![](/img/trans.png)
[英]Python - How to reduce the number of entries per row or symmetric matrix by keeping K largest values
[英]How to pick the largest number in a matrix of lists in python?
我有一个列表列表,其中前两个充当“矩阵”,在这里我可以访问第三个列表
list3 = m[x][y]
第三个列表包含字符串和数字,但每个列表的大小和结构都相同。 让我们将此列表称为“感兴趣的数量”中的特定条目。 此数字在此列表中始终具有相同的索引!
如何获得对Python感兴趣的数量最大的列表的“坐标”(x,y)的最快方法是什么?
谢谢!
(所以,实际上,我正在尝试为所有x&y选择m [x] [y] [k]中最大的数字,其中k是固定的,并“知道”其地址是什么)
max((cell[k], x, y)
for (y, row) in enumerate(m)
for (x, cell) in enumerate(row))[1:]
另外,您可以将结果直接分配给几个变量:
(_, x, y) = max((cell[k], x, y)
for (y, row) in enumerate(m)
for (x, cell) in enumerate(row))
这是O( n 2 ),顺便说一句。
import itertools
indexes = itertools.product( xrange(len(m)), xrange(len(m[0]))
print max(indexes, key = lambda x: m[x[0]][x[1]][k])
或使用numpy
import numpy
data = numpy.array(m)
print numpy.argmax(m[:,:,k])
如果您对加快python的操作速度感兴趣,那么您确实需要研究numpy。
假设“兴趣数量”在列表中的已知位置,并且最大值将为非零,
maxCoords = [-1, -1]
maxNumOfInterest = -1
rowIndex = 0
for row in m:
colIndex = 0
for entry in row:
if entry[indexOfNum] > maxNumOfInterest:
maxNumOfInterest = entry[indexOfNum]
maxCoords = [rowIndex,colIndex]
colIndex += 1
rowIndex += 1
是一种幼稚的方法,其矩阵大小为O(n 2 )。 由于必须检查每个元素,因此这是最快的解决方案。
@Marcelo的方法更肉质,但可读性较低。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.