random - 如何从列表中获取特定数字?
问题描述
我想随机化列表中的单词,如果随机化的单词等于剪刀,我希望游戏告诉我我赢了但我找不到解决方案,你能告诉我哪里做错了吗?
我已经尝试过“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”。
解决方案
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!")
推荐阅读
- kotlin - 自动调整小数格式位置作为kotlin中的输入格式?
- python - 如何在文本中提及成员?不和谐机器人 python
- sql - 我怎样才能找到所有监视器购买(不是监视器 ID 值,而是应该使用术语“监视器”)
- sql - Postgres Join 查询引用自身的表
- php - 如何使用 laravel 中的 query() 函数对两个日期之间的数据进行排序
- python - 在python中找到一个原像需要多长时间
- python - 如何抓取隐藏在可折叠元素内的数据?
- pydeck - 将标题放在 pydeck 图上的方法?
- php - PHP 不会在 BDD 上获得 ID
- wpf - wpf 应用程序在安装时不检查更新