Python 无法分配给列表理解?
我一直在为学校评估编写一个游戏,所以请原谅基本代码。我的问题是,我在main.py的第151行上遇到了一个错误,说SyntaxError:cannotassigntolist-comprehension。此函数仅供参考Python 无法分配给列表理解?,python,list-comprehension,python-2.x,Python,List Comprehension,Python 2.x,我一直在为学校评估编写一个游戏,所以请原谅基本代码。我的问题是,我在main.py的第151行上遇到了一个错误,说SyntaxError:cannotassigntolist-comprehension。此函数仅供参考 def winner(score1,score2,score3,score4,score5): global players string = 'total' string2 = 'score' [string+str(k) for k in range(0,players)]
def winner(score1,score2,score3,score4,score5):
global players
string = 'total'
string2 = 'score'
[string+str(k) for k in range(0,players)] = abs(200 - [string2+str(p) for p in range(0,players)])
king = 100000
counter = 0
for h in range (0,players):
if total[h] < king:
king = total[h]
counter = counter + 1
print ('The winner is ' + player[counter] + ' with a score of ' + str(score[counter - 1]))
print 'Congrats!'
print 'Want to play again?'
有人能简单地解释一下我做错了什么吗?我想你想要的是
def winner(scores):
totals = [abs(200 - score) for score in scores]
max_total = max(totals)
max_index = totals.index(max_total)
best_score = scores[max_index]
best_player = max_index + 1
print("The winner is player {} with a score of {}".format(best_player, best_score))
你可以这样称呼它
>>> winner([-300, 100, 400, -700])
The winner is player 4 with a score of -700
对您正在尝试分配给列表。这就是你的错误的根源。我不知道如何修复它?我找不到任何来源可以解释
[范围内k的string+str(k)(0,玩家)]
不能在=
的左侧。一旦你处理了这个问题,就会出现另一个错误-你试图从200
中减去列表理解的结果,而列表理解的结果总是列表
。这将抛出TypeError
,因为int
和list
类型之间不支持减法。解决方案很简单。不要分配给列表理解。如果您想要更多,那么您必须签出,并提供一个,特别是,解释您的代码应该做什么。这在一定程度上是有效的。唯一的问题是,它显示最好的分数是200,并且只显示玩家为赢家,即使有其他玩家。抱歉,如果这是一个简单的修复,我是相当新的编码。
>>> winner([-300, 100, 400, -700])
The winner is player 4 with a score of -700