opponent = [1, 1, 1, 1, 1, 1]
I want just the first element in my list 'opponent', therefore I then code:
opponent = int(opponent[0])
I use this to then count the number of 'opponent's there are in one of my other lists.
if wongames.count(opponent) == 2:
...blablabla
It says my submission raised an exception of type IndexError at the line. 'opponent = int(opponent[0])'.
Why is this? How do I fix this? :(
Your list of opponents is called opponent
, and later on in your code you do:
opponent = int(opponent[0])
overriding the earlier opponent
list, so now the opponent
name refers to an integer instead.
Next time you do the same again:
opponent = int(opponent[0])
You're trying to access [0]
index of an integer, which obviously doesn't work because integers cannot be indexed.
Solution: Simply use a different name for the two variables. I'd call the list opponents
instead:
opponents = [1, 1, 1, 1, 1]
opponent = opponents[0]
Notice that since they're already integers in the list, you don't need int()
. You only need to use int()
if you want to convert it from one type to another, for example if it was a string '0'
instead of an integer 0
I am not sure what's happening there, but I suspect the indexError
is because you are assigning the same opponent
variable to pick the element from the list opponent
.
If you run this code snippet for the second iteration, variable opponent
is not a list anymore, maybe that is the reason for the error. Try changing assigning the value to a new variable.
opponent = [1, 1, 1, 1, 1, 1]
## Code block
opponent = int(opponent[0]) # Now opponent is not a list, just a number
if wongames.count(opponent) == 2:
# do something
If the code block is executing for the second time, the error occurs. Try changing the code to something as follows,
opponent = [1, 1, 1, 1, 1, 1]
first_opponent = int(opponent[0])
if wongames.count(first_opponent) == 2:
# do something
Hope this helps! :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.