[接受列表的玩家类别,然后继续寻找得分最高的玩家。]
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def best_score(list):
i = 0
while i < len(list):
n = list[i] #list[1] = (Bratt, 250) #list[2] = Lisa 150
s = list[i].score #list 1. score = 250 #list[2].score = 150
ace = list[0] #homer 50 #homer 50
hs = 0
if s > hs: #if s(250>0): #if s(list[2].score) > hs(250): nothing suppsoed to happen
ace = n #ace(homer) = n(list1) aka bratt #ace(bratt) != n because above
hs = s #hs(0) = s(list1) = 250 #hs(250) != list[2]150
#hs is now 250
i += 1
return ace
p1 = Player('Homer', 50)
p2 = Player('Bart', 250)
p3 = Player('Lisa', 150)
ls = [p1, p2, p3]
best = Player.best_score(ls)
msg = '{} has the best score, with {} points!'.format(best.name, best.score)
print(msg) # Bart has the best score, with 250 points!
由于某些原因,我的代码未返回最高的球员得分和姓名。相反,它为我提供了最新的球员得分和姓名。 我尝试通过循环检查它,但我哪里出错了仍然没有意义。
答案 0 :(得分:0)
我们可以专注于代码的这一部分:
dfslices <- structure(list(X0035.A061 = c(19.48052, 2.96846, 0, 0), X0094.B116 = c(8.127208,
9.069494, 2.237927, 0), X0314.A038 = c(36.8243243, 7.4324324,
0.3378378, 1.6891892)), .Names = c("X0035.A061", "X0094.B116",
"X0314.A038"), class = "data.frame", row.names = c("verylow",
"low", "medium", "high"))
在撰写时,while i < len(list):
hs = 0
if s > hs:
ace = n
hs = s
与s > hs
相同,因此条件对于列表中所有得分大于零的项目均为true。
要保持最大值,应该在进入循环之前定义一次,如下所示:
s > 0
通过此更改,hs = 0
while i < len(list):
if s > hs:
ace = n
hs = s
的值将在hs
循环的迭代过程中保留,最后将保持最佳分数while
。