鱼C论坛

 找回密码
 立即注册
查看: 2257|回复: 1

这句怎么理解,有没有大神讲解下

[复制链接]
发表于 2020-1-30 21:57:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
请问elif user_choice == punches[punches.index(computer_choice)-1]: 这句怎么理解,有没有大神讲解下
  1. import random

  2. # 出拳
  3. punches = ['石头','剪刀','布']
  4. computer_choice = random.choice(punches)
  5. user_choice = ''
  6. user_choice = input('请出拳:(石头、剪刀、布)')  # 请用户输入选择
  7. while user_choice not in punches:  # 当用户输入错误,提示错误,重新输入
  8.     print('输入有误,请重新出拳')
  9.     user_choice = input()

  10. # 亮拳
  11. print('————战斗过程————')
  12. print('电脑出了:%s' % computer_choice)
  13. print('你出了:%s' % user_choice)

  14. # 胜负
  15. print('—————结果—————')
  16. if user_choice == computer_choice:  # 使用if进行条件判断
  17.     print('平局!')
  18. # 电脑的选择有3种,索引位置分别是:0石头、1剪刀、2布。
  19. # 假设在电脑索引位置上减1,对应:-1布,0石头,1剪刀,皆胜。
  20. elif user_choice == punches[punches.index(computer_choice)-1]:
  21.     print('你赢了!')
  22. else:
  23.     print('你输了!')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-1-30 22:01:15 | 显示全部楼层
elif user_choice == punches[punches.index(computer_choice)-1]

一层一层看:

punches.index(computer_choice):获取 punches 中 computer_choice 出现的索引。

punches[punches.index(computer_choice)-1]:获取 punches 中下标为 punches.index(computer_choice) 再减 1 的元素。

user_choice == punches[punches.index(computer_choice)-1]:如果 user_choice 等于 punches[punches.index(computer_choice)-1] 则执行下面的代码。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-22 01:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表