我该如何解决? “不支持的操作数类型”

时间:2019-07-29 11:26:14

标签: python

import random 
athletes = ["John","Mike","Jack","Steve","Bob"]
judges = ["Judge1","Judge2","Judge3"]
numbers = ["1","2","3","4","5","6","7","8","9","10"]
def score():
  random.shuffle(numbers)
  judge_scores = numbers[0] + numbers[1] + numbers[2]
  final = int(judge_scores)
  final_2 = sum(final)
  print(final_2)


i = 0
while i <= 4:
    athlete = athletes[i]
    print(athlete + " scored:")
    score()
    i += 1
    if i > 4:
        break

我正在尝试使此代码返回法官为每个运动员提供的随机分数的总和,但是我遇到一个错误,说

  

int对象不可迭代。

我没有运气就做了一些改动,这是我认为最接近的原始代码:

import random 
athletes = ["John","Mike","Jack","Steve","Bob"]
judges = ["Judge1","Judge2","Judge3"]
numbers = ["1","2","3","4","5","6","7","8","9","10"]
def score():
  random.shuffle(numbers)
  judge_scores = numbers[0] + numbers[1] + numbers[2]
  final = sum(judge_scores)
  print(final)


i = 0
while i <= 4:
    athlete = athletes[i]
    print(athlete + " scored:")
    score()
    i += 1
    if i > 4:
        break

我再次遇到错误。这次我收到此错误:

  

TypeError:+不支持的操作数类型:“ int”和“ str”

4 个答案:

答案 0 :(得分:2)

您是否有一个包含数字的列表,请尝试将数字更改为 数字= [1,2,3,4,5,6,7,8,9,10]

答案 1 :(得分:2)

您可以像这样将数字列表中的字符串值更改为int:

import random 
athletes = ["John","Mike","Jack","Steve","Bob"]
judges = ["Judge1","Judge2","Judge3"]
numbers = [1,2,3,4,5,6,7,8,9,10]
def score():
  random.shuffle(numbers)
  judge_scores = numbers[0] + numbers[1] + numbers[2]

  print(judge_scores)


i = 0
while i <= 4:
    athlete = athletes[i]
    print(athlete + " scored:")
    score()
    i += 1
    if i > 4:
        break

或者您可以使用

import random 
athletes = ["John","Mike","Jack","Steve","Bob"]
judges = ["Judge1","Judge2","Judge3"]
numbers = ["1","2","3","4","5","6","7","8","9","10"]
def score():
  random.shuffle(numbers)
  judge_scores = int(numbers[0]) + int(numbers[1]) + int(numbers[2])

  print(judge_scores)


i = 0
while i <= 4:
    athlete = athletes[i]
    print(athlete + " scored:")
    score()
    i += 1
    if i > 4:
        break

答案 2 :(得分:1)

判断字符串中的分数,sum适用于int类型,您需要先将stitng转换为int然后进行求和运算

import random 
athletes = ["John","Mike","Jack","Steve","Bob"]
judges = ["Judge1","Judge2","Judge3"]
numbers = ["1","2","3","4","5","6","7","8","9","10"]
def score():
  random.shuffle(numbers)
  judge_scores = [numbers[0] , numbers[1] , numbers[2]]
  final = sum(map(int,judge_scores))
  print(final)


i = 0
while i <= 4:
    athlete = athletes[i]
    print(athlete + " scored:")
    score()
    i += 1
    if i > 4:
        break

答案 3 :(得分:1)

sum进行迭代,并对其值求和。在您的情况下,numbers包含字符串,因此它将字符串串联在一起:('2', '5', '7')转到'257'。 更改numbers中的[1,2,...]列表,一切正常。

此外,您只需输入

numbers = list(range(10))