python - 如何在 Python 中检查两个随机生成的字符串是否匹配
问题描述
因为我正在尝试编写一个简单的脚本来检查使用“选择”函数生成的两个字符串是否匹配。“选择”功能从给定列表中挑选字母。我在使用 while 循环时遇到问题。这是我的尝试:
from random import choice
list1 = ['a', 'r', 'l', 'd', 'n', 'm']
ticket = ''
for i in range(3):
ticket += choice(list1)
print(f"This is the winning ticket: {ticket}\n")
my_tickets = [] #store here the tickets that don't match
my_ticket = ''
for i in range(3):
my_ticket += choice(list1)
print(f"The ticket you buy is: {my_ticket}")
active = True
while active:
for i in range(3):
my_ticket += choice(list1)
if my_ticket == ticket:
active = False
print("Congratulations, you got the winning ticket!!")
else:
print('Try again')
你能帮我找出错误在哪里吗?是否可以在不使用字符串模块的情况下使该脚本工作?谢谢
解决方案
您还没有描述出了什么问题,但我建议在 else 语句中将 my_ticket 的值设置回 '' 并附加到 my_tickets 变量,因为注释表明了这一点,但您最终不会这样做。
推荐阅读
- r - 正确使用 tryCatch 跳过绘图错误
- java - 将变量从js文件传递到spring控制器
- java - @Valid,@NotEmpty 在我的 Spring 应用程序中不起作用
- javascript - 如何将引导 css 样式表合并到我的 express/node js 中?
- kubernetes - 大使服务保持“待定”
- apache-spark - 如何在 pyspark 中按列对数据帧进行分区以进行进一步处理?
- r - 在 R 中,optim 不会返回函数的最大值,并且 uniroot 返回错误的值
- javascript - d3 remove 和 exit 没有正确删除堆叠栏中的项目
- javascript - 如何在 App Scripts 中将我的第一列带到我的自动电子邮件中?
- go - 无法在 vscode apple m1 中调试 Golang