不能用“for”来赋值

2024-09-24 12:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python创建一个Yahtzee程序。此函数用于执行用户选择的操作(用户输入一个数字,然后选择适当的列表项)。我刚到了一组数字相加的部分(Yahtzee卡的顶部有1,2等)。我做了一个循环,在列表dicevalues(一个“掷骰子”数字的随机列表;在程序的前面声明)中每找到一个1加一个分数。在

我在for 1 in dicevalues:行得到错误。上面写着SyntaxError: cannot assign to literal。我查过这个错误,但我搞不懂。我在这里解释的是,程序将为for中的每个值1运行代码,但我不太确定是否可以用这种方式使用for循环。在

def choiceAction():
  if options[choice] == "Chance (score total of dice).":
    global score
    score += (a + b + c + d + e)
  if options[choice] == "YAHTZEE!":
    score += 50
  if options[choice] == "Large straight":
    score += 40
  if options[choice] == "Small straight.":
    score += 30
  if options[choice] == "Four of a kind (total dice score).":
    score += (a + b + c + d + e)
  if options[choice] == "Three of a kind (total dice score).":
    score += (a + b + c + d + e)
  if options[choice] == "Full house.":
    score += 25
  if options[choice] == "Add all ones.":
    for 1 in dicevalues: # <-- SyntaxError: can't assign to literal
      score += 1

是否可能由于某种原因1不能在for声明中?在


Tags: of用户程序声明列表forif数字
2条回答

错误

当您编写for x in dicevalues:时,您会迭代dicevalues,并将每个元素放入变量x,因此x不能被1替换。这就是为什么会出现错误SyntaxError: can't assign to literal。在

解决方案

这里有几种解决方案可以实现您想要的效果:

dicevalues = [2, 1, 3, 6, 4 ,1, 2, 1, 6]

# 1. Classic 'for' loop to iterate over dicevalues and check if element is equal to 1
score = 0
for i in dicevalues:
    if i == 1:
        score += 1
print(score) # 3

# 2. Comprehension to get only the elements equal to 1 in dicevalues, and sum them
score = 0
score += sum(i for i in dicevalues if i == 1)
print(score) # 3

# 3. The 'count()' method to count the number of elements equal to 1 in dicevalues
score = 0
score += dicevalues.count(1)
print(score) # 3

如果不想使用dicevalues中的项,可以使用占位符

for _ in dicevalues:

相关问题 更多 >