如何确保单词的颜色不是单词所说的颜色

2024-09-29 21:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在代码中进行Stroop测试已经有一段时间了,除了一件事之外,我几乎已经完成了它。在6个测试的最后2个测试中,彩色单词需要显示与单词不同的颜色(例如,如果单词为“绿色”,则颜色不能为绿色)

我尝试过更改我使用的列表,并尝试过用颜色书写发短信是因为我希望它能起作用,但没有。每次我尝试修改列表或玩它们时,情况都会变得更糟,我不知道它到底是如何工作的

if numbertest == 6:
  tina.color('black');style = ('Arial', 20, 'bold');tina.write('Instructions in console below', font=style, align='center')
  print ('In 10 seconds you will be shown a colored word on the screen. Type the first letter of the COLOR, then hit enter. Then hit enter a second time, and the next word will be shown.')
  time.sleep(10)
  tina.clear()
  while nooftrials < 10:
    index = random.randint(0, len(colors) -1)
    color = colors[index]
    text = random.choice(texts)
    tina.color(color);style = ('Arial', 20, 'bold');tina.write(text, font=style, align='center')
    t0 = time.time()
    answer = str(raw_input("Letter of color: "))
    nooftrials += 1

预期结果是tina.write(text...)将写一个单词,而tina.color(color)将是与文本不同的颜色,例如,如果文本为“蓝色”,则单词的颜色不是蓝色。然而,目前它是随机的,有时会出现一致的集合,即使这部分是指不同的单词和颜色


Tags: thetext列表timestyle颜色单词write
1条回答
网友
1楼 · 发布于 2024-09-29 21:28:46

选择一种随机颜色,然后确保选择一个随机单词,只要它与所选颜色不同(或相反):

color = random.choice(colors)
text = color
while text == color:
    text = random.choice(texts)

在行动中:

import random

colors = list(range(2))
texts = list(range(2))

color = random.choice(colors)
text = color
while text == color:
    print(f'color is {color}, text is {text}')
    text = random.choice(texts)

print(f'finally, color is {color}. text is {text}')

样本输出:

color is 1, text is 1
finally, color is 1. text is 0


这可能是次优的

另一种选择是选择一种颜色,然后将其从texts中删除,然后再选择一个随机单词。这将保证colortext是不同的。只要texts中的单词是唯一的,这将起作用,因为list.remove只删除第一个出现的单词

import random

colors = list(range(5))
texts = list(range(5))

color = random.choice(colors)
texts.remove(color)
text = random.choice(texts)

print(f'finally, color is {color}. text is {text}')

样本输出

finally, color is 4. text is 2

相关问题 更多 >

    热门问题