此代码输出00000000,但我认为它将输出00000011,因为最后两个索引满足if条件。
import pygame
numbers = [pygame.Color("#FFFFFF"),
pygame.Color("#FFFFFF"),
pygame.Color("#FFFFFF"),
pygame.Color("#FFFFFF"),
pygame.Color("#FFFFFF"),
pygame.Color("#FFFFFF"),
pygame.Color("#FF0000"),
pygame.Color("#FF0000")]
x = 0
binary = ""
for number in numbers:
print(number)
if numbers[x] == pygame.Color("#FF0000"):
binary += "1"
elif numbers[x] == pygame.Color("#FFFFFF"):
binary += "0"
print("after: ", binary)
答案 0 :(得分:1)
将循环更改为此:
for number in numbers:
print(number)
if number == pygame.Color("#FF0000"):
binary += "1"
elif number == pygame.Color("#FFFFFF"):
binary += "0"
numbers[x]
将始终指向第一个元素,因为您没有递增x
。因此,将numbers[x]
更改为number
。
答案 1 :(得分:0)
如果要使用索引,可以更改如下代码:
binary = ""
for x, number in enumerate(numbers):
print(number) # number = numbers[x]
if numbers[x] == pygame.Color("#FF0000"):
binary += "1"
elif numbers[x] == pygame.Color("#FFFFFF"):
binary += "0"
print("after: ", binary)