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. 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"
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))
CodePudding user response:
You can use a list comprehension to create a new list with the binary representations of each number in the original list.
print([bin(x) for x in numRandom])
CodePudding user response:
As the error says, numRandom
is a list, not an integer. Specifically, it's a list of ten random int
s.
To apply the bin
function to the first element of the list, you could do:
print(bin(numRandom[0]))
You could iterate over the list and do this to each one with a for
loop:
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])
CodePudding user response:
Using Map
print([*map(bin, random.sample(y, 10))])
Or Using List Comprehension
print([bin(x) for x in random.sample(y, 10)])