[英]'list' object cannot be interpreted as an integer - Is there a way to convert a list to integers?
now I am new to the python language, only that in one subject they ask us to do the homework with this language and it is to investigate on our own.现在我是 python 语言的新手,只是在一个主题中,他们要求我们用这种语言做作业,并且是我们自己调查。 In this part of code I first declare the range with the range (0-1024) method, and the random numbers are generated with the sample method, and I believe that these are saved in a list, so what I want to do next is that these Numbers that were generated randomly convert them to binary, but I get this error: "TypeError: 'list' object cannot be interpreted as an integer"
这部分代码我先用range(0-1024)方法声明范围,用sample方法生成随机数,相信这些都是保存在一个列表中的,所以接下来要做的是这些随机生成的数字将它们转换为二进制,但我收到此错误:“类型错误:'列表'对象不能解释为整数”
So I don't know if there is a way to convert a list to whole numbers or I don't know what else they would recommend me to do ...所以我不知道是否有办法将列表转换为整数,或者我不知道他们还会推荐我做什么......
This is my code:这是我的代码:
y = list(range(0, 1024))
numRandom = sample(y, 10)
print(numRandom)
print(bin(numRandom))
您可以使用列表理解来创建一个新列表,其中包含原始列表中每个数字的二进制表示。
print([bin(x) for x in numRandom])
As the error says, numRandom
is a list, not an integer.正如错误所说,
numRandom
是一个列表,而不是一个整数。 Specifically, it's a list of ten random int
s.具体来说,它是一个包含十个随机
int
的列表。
To apply the bin
function to the first element of the list, you could do:要将
bin
函数应用于列表的第一个元素,您可以执行以下操作:
print(bin(numRandom[0]))
You could iterate over the list and do this to each one with a for
loop:您可以遍历列表并使用
for
循环对每个列表执行此操作:
for num in numRandom:
print(bin(num))
Or you could build a list of binary representations with a list comprehension:或者您可以使用列表理解构建二进制表示列表:
print([bin(num) for num in numRandom])
print([*map(bin, random.sample(y, 10))])
print([bin(x) for x in random.sample(y, 10)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.