此代码输出 00000000,但我认为它会输出 00000011,因为最后 2 个索引符合 if 条件。import pygamenumbers = [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 = 0binary = ""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)
2 回答
沧海一幻觉
TA贡献1824条经验 获得超5个赞
将您的循环更改为:
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.
慕哥9229398
TA贡献1877条经验 获得超6个赞
如果你想使用索引,你可以像这样更改代码:
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)
添加回答
举报
0/150
提交
取消