首页 > 解决方案 > 如何从列表中获取特定数字?

问题描述

我想随机化列表中的单词,如果随机化的单词等于剪刀,我希望游戏告诉我我赢了但我找不到解决方案,你能告诉我哪里做错了吗?

我已经尝试过“if 3 in my_list:”但仍然找不到解决方案

import random

my_list = ["rock", "paper", "scissor"]
random.choice(my_list)
print(random.choice(my_list))

if random.choice(my_list) == my_list[3]:
    print("You Won!")
else:
    print("You Lost!")

当 random.choice 是列表中的剪刀时,我想打印“You Won”。

标签: randompython-3.7

解决方案


You should get this error IndexError: list index out of range because my_list have total 3 items,

my_list[0] -> "rock"

my_list[1] -> "paper"

my_list[2] -"scissor"

so result of random.choice from my_list always will be my_list[0] or my_list[1] or my_list[2]

In this line if random.choice(my_list) == my_list[3]: checking if value of random.choice() is equal to my_list[3] but theres no item in 3rd position of ur list.

"scissor" position in my_list[2]. so this should work,

import random
my_list = ["rock", "paper", "scissor"]
rand_item = random.choice(my_list)

if rand_item == my_list[2]:
    print("You Won!")
else:
    print("You Lost!")

推荐阅读