gpt4 book ai didi

python - 随机数数据可视化逻辑存在问题

转载 作者:行者123 更新时间:2023-12-01 01:31:43 25 4
gpt4 key购买 nike

所以我最近在观看了一个很酷的 Numberphile 视频后了解了数据可视化,我想用随机数制作我自己的小数据可视化。我的想法是,我有一个随机整数列表,并根据数字绘制一个不同颜色的圆圈。下面的代码解释了颜色键。

但是,我的代码似乎存在逻辑问题。代码运行没有错误,但根据我之前的描述,我的程序无法正常工作。首先,我的列表中有 10 个整数,但程序中只绘制了 6 个。另外,色彩有点少。感谢任何帮助,谢谢。

import pygame
pygame.init()

## COLOR KEY
# 0 - Black
# 1 - White
# 2 - Red
# 3 - Orange
# 4 - Yellow
# 5 - Green
# 6 - Blue
# 7 - Indigo
# 8 - Violet
# 9 - dark blue

display_width = 1000
display_height = 500
display = pygame.display.set_mode((display_width,display_height))

black = 0,0,0
white = 255,255,255
red = 255,0,0
orange = 255,165,0
yellow = 255,255,0
green = 0,255,0
blue = 0,0,255
indigo = 29,0,51
violet = 128,0,128
darkblue = 0,200,0

random_list = [9,8,5,9,4,7,5,1,9,0]
def programLoop():
exitProgram = False
while not exitProgram:

for evt in pygame.event.get():
if evt.type == pygame.QUIT:
pygame.quit()
quit()

startN = 100

display.fill(white)
for n in random_list:
color = black
if random_list[n] == 0:
color = black

if random_list[n] == 1:
color = white

if random_list[n] == 2:
color = red

if random_list[n] == 3:
color = orange

if random_list[n] == 4:
color = yellow

if random_list[n] == 5:
color = green

if random_list[n] == 6:
color = blue

if random_list[n] == 7:
color = indigo

if random_list[n] == 8:
color = violet

if random_list[n] == 9:
color = darkblue

pygame.draw.circle(display,color,[n * 50 + startN,250],10)

pygame.display.update()

programLoop()

最佳答案

调试程序的第一步是打印n, color, n*50 + startN。您会发现您正在迭代 random_list 中的索引,而不是您期望的范围。因此第一个数字是 9,您检查 if random_list[9] == 0,即 True,它设置 color = black 并显示它550。

您可以迭代范围 for n in range(len(random_list)): 来解决此问题。

<小时/>

我建议将颜色放入列表或字典中,然后迭代 enumerated 随机列表。然后您同时获得数字n和颜色索引,并且可以通过以下方式访问颜色:color = color[color_index]

更新后的代码:

darkblue = 0,0,200  # Your darkblue was green.
# Put the colors into a list.
colors = [black, white, red, orange, yellow, green, blue, indigo, violet, darkblue]
random_list = [9,8,5,9,4,7,5,1,9,0]

def programLoop():
clock = pygame.time.Clock() # A clock to limit the frame rate.
exitProgram = False
while not exitProgram:
for evt in pygame.event.get():
if evt.type == pygame.QUIT:
exitProgram = True

startN = 100

display.fill((200, 200, 200))
# Now enumerate the list, so that you'll get n and the color index
# at the same time.
for n, color_index in enumerate(random_list):
color = colors[color_index]
pygame.draw.circle(display, color, [n*50 + startN, 250], 10)

pygame.display.update()
clock.tick(60) # Limit the frame rate to 60 FPS.

programLoop()
pygame.quit()

关于python - 随机数数据可视化逻辑存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52799331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com