我有这个列表清单:
a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
我想在每列中找到最大值,如下面的输出:
"Max value of column [0]": 6 (at index [2][0])
"Max value of column [1]": 8 (at index [1][1])
"Max value of column [2]": 9 (at index [2][2])
我尝试了max(enumerate(a), key=operator.itemgetter(1))
,但这会返回(2, [6,3,9])
,就像说[0]
位置具有最大值的嵌套列表是位于列表的索引[2]
的嵌套列表a
。
答案 0 :(得分:4)
使用zip
转置您的列表,并在每个“子元组”上调用max
。
>>> a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
>>> map(max, zip(*a))
[6, 8, 9]
答案 1 :(得分:1)
pandas
救援
df = pd.DataFrame(a)
for k, i, m in zip(df.columns, df.idxmax(), df.max()):
print('"Max value of column [%i]": %i (at index [%i][%i]' % (k, m, k, i))
如果您想稍后重复使用最大值的'坐标',您可以执行类似
的操作result = {k: (i, m,) for k, i, m in zip(df.columns, df.idxmax(), df.max()) }
或
result = {k: {'index': i, 'max': m,} for k, i, m in zip(df.columns, df.idxmax(), df.max()) }
答案 2 :(得分:1)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='pin-holder'>
<div class='img-frame'><a href='#'><img src='pins/pic01.png' height='300' width='300'/></a></div>
<div class='hidden-title'><h1>PLEASE WORK!</h1></div>
</div>
<div class='pin-holder'>
<div class='img-frame' id='frame01'><a href='#'><img src='pins/pic02.png' height='300' width='300'/></div>
<div class='hidden-title'><h1>PLEASE WORK!</h1></div>
</div>
,
numpy
您想要的最终输出为In [27]: a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
In [28]: import numpy as np
In [29]: an = np.array(a)
In [30]: np.max(an,axis=0)
Out[30]: array([6, 8, 9])
+ list comprehension
numpy
不使用["Max value of column [%s]: %s (at index [%s][%s])" %(np.where(an == item)[1][0],item,np.where(an == item)[0][0],np.where(an == item)[1][0]) for item in np.max(an,axis=0)]
,
list comprehension
结果:
for item in np.max(an,axis=0):
indexs = np.where(an == item)
print "Max value of column [%s]: %s (at index [%s][%s])" %(indexs[0][0],item,indexs[0][0],indexs[1][0])
答案 3 :(得分:1)
我非常喜欢 @timegeb 对$ python test.py
$95.00
的回答,但更多的是手动替代,假设所有数组的长度相同:
zip
答案 4 :(得分:0)
另一种转置列表并获取最大值的方法:
a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
[max([item[k] for item in a]) for k in range(len(a))]