TypeError:“列表"对象不能解释为整数 [英] TypeError: 'list' object cannot be interpreted as an integer

查看:84
本文介绍了TypeError:“列表"对象不能解释为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

playSound函数获取一个整数列表,并将为每个不同的数字播放声音.因此,如果列表中的数字之一是1,则1具有将播放的指定声音.

The playSound function is taking a list of integers, and is going to play a sound for every different number. So if one of the numbers in the list is 1, 1 has a designated sound that it will play.

def userNum(iterations):
  myList = []
  for i in range(iterations):
    a = int(input("Enter a number for sound: "))
    myList.append(a)
    return myList
  print(myList)

def playSound(myList):
  for i in range(myList):
    if i == 1:
      winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

我收到此错误:

TypeError: 'list' object cannot be interpreted as an integer

我尝试了几种方法将列表转换为整数.我不太确定我需要更改什么.我相信,有一种更有效的方法可以做到这一点.任何帮助将不胜感激.

I have tried a few ways to convert the list to integers. I am not too sure what I need to change. I am sure that there is a more efficient way of doing this. Any help would be very greatly appreciated.

推荐答案

错误消息通常准确地表示他们所说的话.因此,必须非常仔细地阅读它们.当您执行此操作时,您会发现实际上似乎并没有在抱怨您的列表包含的对象,而是实际上是在抱怨什么样的对象. >是.这并不是说它希望您的列表包含整数(复数),而是希望您的列表是一个整数(单数),而不是任何东西的列表.而且,由于您不能将列表转换为单个整数(至少,在这种情况下不是有意义的方式),因此您不应该尝试.

Error messages usually mean precisely what they say. So they must be read very carefully. When you do that, you'll see that this one is not actually complaining, as you seem to have assumed, about what sort of object your list contains, but rather about what sort of object it is. It's not saying it wants your list to contain integers (plural)—instead, it seems to want your list to be an integer (singular) rather than a list of anything. And since you can't convert a list into a single integer (at least, not in a way that is meaningful in this context) you shouldn't be trying.

所以问题是:为什么解释器似乎想要将您的列表解释为整数?答案是您要将列表作为输入参数传递给range,该参数需要一个整数.不要那样做请说for i in myList.

So the question is: why does the interpreter seem to want to interpret your list as an integer? The answer is that you are passing your list as the input argument to range, which expects an integer. Don't do that. Say for i in myList instead.

这篇关于TypeError:“列表"对象不能解释为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆