[英]How to find the min and max values of an index in nested lists with matching strings?
[英]How to find max value in nested lists and its index, based on column number?
假設我有以下列表列表: a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
1、7、2 a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
5、8、4 a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
6、3、9 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]
位置的最大值是位於列表a
索引[2]
的那個。
用zip
列表,並在每個“子元組”上調用max
。
>>> a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
>>> map(max, zip(*a))
[6, 8, 9]
救援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()) }
使用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])
結果:
['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])']
我真的很喜歡@timegeb的zip
答案,但是假設所有數組的長度相同,這是一個更簡單的選擇:
a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
maxArray = []
for i in range(len(a[0])):
maxArray.append(max([x[i] for x in a]))
print(maxArray) # prints [6,8,9]
換位列表並獲得最大值的另一種方法:
a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
[max([item[k] for item in a]) for k in range(len(a))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.