我解決了這個問題,但不是以可接受的方式,如何改進代碼?
問題是創建成績串列功能,我會得到最高成績,我們需要在索引之間進行比較
def 等級(串列 1,串列 2,串列):
highest=[]
newlist1= []
newlist1.append(list1[0])
newlist1.append(list2[0])
newlist1.append(list3[0])
max1=0
for i in newlist1:
if i > max1:
max1= i
newlist2= []
newlist2.append(list1[1])
newlist2.append(list2[1])
newlist2.append(list3[1])
max2=0
for i in newlist2:
if i > max2:
max2= i
newlist3= []
newlist3.append(list1[2])
newlist3.append(list2[2])
newlist3.append(list3[2])
max3=0
for i in newlist3:
if i > max3:
max3= i
newlist4= []
newlist4.append(list1[3])
newlist4.append(list2[3])
newlist4.append(list3[3])
max4=0
for i in newlist4:
if i > max4:
max4= i
newlist5= []
newlist5.append(list1[4])
newlist5.append(list2[4])
newlist5.append(list3[4])
max5=0
for i in newlist5:
if i > max5:
max5= i
highest.append(max1)
highest.append(max2)
highest.append(max3)
highest.append(max4)
highest.append(max5)
return(highest)
列印(等級([99,88,77,92,44],[80,100,65,48,87],[75,95,70,96,85]))
答案是:[99, 100, 77, 96, 87]
uj5u.com熱心網友回復:
在 numpy 的二維陣列中,使用 transpose() 是一種獲取值的簡單方法。并且使用 max() 是獲得最高價值的一種簡單方法。
import numpy as np
def grade(list1, list2, list3):
total_list = [list1, list2, list3]
newlist = np.array(total_list).transpose()
highest = []
for data in newlist:
highest.append(max(data))
return highest
if __name__ == "__main__":
print(grade([99,88,77,92,44],[80,100,65,48,87],[75,95,70,96,85]))
uj5u.com熱心網友回復:
我不能使用max,定義自己的函式,然后簡單地遍歷壓縮串列:
def get_max(elems):
MAX = float('-inf')
for e in elems:
if e>MAX:
MAX = e
return MAX
def grade(*lists):
return [get_max(elems) for elems in zip(*lists)]
grade([99,88,77,92,44],[80,100,65,48,87],[75,95,70,96,85])
# [99, 100, 77, 96, 87]
uj5u.com熱心網友回復:
為了簡化它,您可以根據矩陣來思考
[ 1、5、7 2、3、15 8、2、12 ]
現在基本上你想要的是這個矩陣中每一列中的最大值
def highest_grade_among_list(gradelist1,gradelist2,gradelist3):
#ensure the list are of same length
if len(gradelist1) != len(gradelist2) or len(gradelist2) != len(gradelist3) or len(gradelist1) != len(gradelist3):
return "Error: lists are not of same length"
else:
grade_matrix = []
grade_matrix.append(gradelist1)
grade_matrix.append(gradelist2)
grade_matrix.append(gradelist3)
max_grade_in_col = 0
result = []
for i in range(len(gradelist1)):
for j in range(len(grade_matrix)):
if grade_matrix[j][i] > max_grade_in_col:
max_grade_in_col = grade_matrix[j][i]
result.append(max_grade_in_col)
max_grade_in_col = 0
return result
if __name__ == '__main__':
print(highest_grade_among_list([99,88,77,92,44],[80,100,65,48,87],[75,95,70,96,85]))
uj5u.com熱心網友回復:
當您想轉置純 Python 串列時,zip是您的朋友。您可以通過理解得到結果:
[max(lst) for lst in zip([99,88,77,92,44],[80,100,65,48,87],[75,95,70,96,85])]
按預期給出:
[99, 100, 77, 96, 87]
uj5u.com熱心網友回復:
如果只允許 max()
def grade(l1, l2, l3):
return [sorted(z)[-1] for z in zip(l1,l2,l3)]
print(grade([99,88,77,92,44],[80,100,65,48,87],[75,95,70,96,85]))
# [99, 100, 77, 96, 87]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/425645.html
