給出元組的列表:如何在元組列表中找到第一次絕對最大值的索引?
[(-8.33958, -84.01769099999999), (-7.96129, -84.37399199999999), (-8.33958, -83.84126699999999), (-7.96129, -84.19756499999998), (-7.24097, -85.581651), (-6.86267, -85.937952), (-7.24097, -85.405227), (-6.86267, -85.76152499999999), (-9.4382, -83.473767), (-9.4382, -83.473767), (-8.35625, -85.11197399999999), (-9.0599, -83.83006499999999), (-9.0599, -83.83006499999999), (-7.97795, -85.46824499999998), (-8.35625, -84.93524699999999), (-7.97795, -85.29151799999998), (-8.33958, -85.03772699999999), (-8.00311, -88.17046199999997), (-5.88285, -86.59070369999999), (-6.86267, -88.655385), (-9.37174, -86.88101999999999), (-7.34506, -88.24291199999999), (-8.22317, -87.13259099999999), (-7.72054, -86.124309), (-8.35625, -86.131707), (-8.35625, -86.131707), (-7.03703, -88.90182), (-8.51394, -86.422992), (-8.51394, -85.83968999999999), (-9.61255, -85.510092), (-9.89311, -84.10327799999999), (-7.96129, -87.540312), (-9.13791, -86.022645)]
的目的是要找到元組的第一個項目的價值最高的指數。與示例輸入輸出上述的元組的索引(-9.89311, -84.10327799999999)
我已經做了這樣的(但它不返回正確的輸出):
x = [(-8.33958, -84.01769099999999), (-7.96129, -84.37399199999999), (-8.33958, -83.84126699999999), (-7.96129, -84.19756499999998), (-7.24097, -85.581651), (-6.86267, -85.937952), (-7.24097, -85.405227), (-6.86267, -85.76152499999999), (-9.4382, -83.473767), (-9.4382, -83.473767), (-8.35625, -85.11197399999999), (-9.0599, -83.83006499999999), (-9.0599, -83.83006499999999), (-7.97795, -85.46824499999998), (-8.35625, -84.93524699999999), (-7.97795, -85.29151799999998), (-8.33958, -85.03772699999999), (-8.00311, -88.17046199999997), (-5.88285, -86.59070369999999), (-6.86267, -88.655385), (-9.37174, -86.88101999999999), (-7.34506, -88.24291199999999), (-8.22317, -87.13259099999999), (-7.72054, -86.124309), (-8.35625, -86.131707), (-8.35625, -86.131707), (-7.03703, -88.90182), (-8.51394, -86.422992), (-8.51394, -85.83968999999999), (-9.61255, -85.510092), (-9.89311, -84.10327799999999), (-7.96129, -87.540312), (-9.13791, -86.022645)]
index_of_max_abs_j = -1
for i, (j,k) in enumerate(x):
if j*j > index_of_max_abs_j:
index_of_max_abs_j = i
print index_of_max_abs_j
的代碼返回的max(j*j)
索引但那是正確的?與試圖找到max(|j|)
有什麼不同?
但是是否有另一種方法實現相同的輸出?也許與sorted
和reverse
和key
與一些math.abs
? sorted
,reverse
和/或key
更有效嗎?
如果元組列表中的任何項具有相同的值,則返回第一個最大絕對值實例的第一個索引。
您的代碼將'j * j'與*索引*進行比較。那是對的嗎? – DSM
是的,因爲j * j會給出最高的廣場。排名應該和'math.abs()'一樣。對? – alvas
哦,這是不同的!任何想法爲什麼排名是從'math.fabs()'不同於'j * j'? – alvas