![](/img/trans.png)
[英]Creating a while loop within a class and adding user input to list?
[英]Creating a list within a loop
我创建了一个“策划者”风格的游戏,用户可以在其中猜测计算机生成的确切数字序列。
我想添加一个存储先前猜测的功能,以便在进行下一次猜测之前可以将它们重播给用户
在我的脑海中和当前的程序布局中,我认为如果我可以创建一系列“pul”(以前的用户列表)会很好。
例如,当 while 循环运行并且“count”变量增加时,列表会被适当地命名。
cl, 电脑列表
ul,用户列表
ol,输出列表
pul,以前的用户列表
当 count = 0 时,用户输入创建 ul = [1, 3, 4, 8]
pul_0 = ul
'# 所以 pul_0 = [1, 3, 4, 8]
当 count = 1 时,用户为 ul = [2, 2, 9, 0] 创建新列表
pul_1 = ul
'# 所以 pul_1 = [2, 2, 9, 0]
'# 当然 pul_0 仍然 = [1, 3, 4, 8]
任何帮助表示赞赏,提前致谢。
如果需要,这里有一些代码可以提供更多细节,底部的完整程序可以提供更多上下文。
n = int(input("how many numbers to guess? (normally 4)"))
att = int(input("how many attempts? (normally 10)"))
count = 0
while count < att:
ul = [int(input()) for i in range(n)]
pul(count) = ul
count = count + 1
我已经阅读了一些关于使用字典来解决这个问题的内容,但没有让它们为我工作, 在 python 的 for 循环中创建唯一名称列表
{'pul_{}'.format(count):[] for i in ul}
完整程序如下
n = int(input("how many numbers to guess? (normally 4)"))
att = int(input("how many attempts? (normally 10)"))
cl = [randint(0, 9) for i in range(n)]
wincount = 0
count = 0
while count < att:
print(att-count, "attempts remaining. Please enter",n, "numbers, pressing enter between each")
ul = [int(input()) for i in range(n)]
wincount = 0
nearcount = 0
for i in range (n):
if cl[i] == ul[i]:
wincount = wincount + 1
for j in range (n):
if cl[i] == ul[j]:
nearcount += 1
nearcount = nearcount - wincount
if wincount == n:
print("winner")
count = att + 1
if wincount != n:
print("you have", wincount,"correct numbers in the correct positions")
print("you have a further", nearcount,"correct numbers, but they are in the wrong positions")
count = count + 1
if count == att:
print("no more attempts, game over")
print("btw the correct answer was", cl)
elif count == att + 1:
print("nice 1")
'''
I have read a small amount about using a dictionary to try and solve this issue, but i played around with it a little and didn't get very far.
Thanks in advance!
这是您修改的代码
n = int(input("how many numbers to guess? (normally 4)"))
att = int(input("how many attempts? (normally 10)"))
count = 0
pul = {} # here're your previous lists, currently empty
while count < att:
ul = [int(input()) for i in range(n)]
pul[count] = ul # you can use more flexible key value, as you mentioned
count = count + 1
# if you need to replay lists - you just use your "pul" dict
for i in range(count):
print(f'your № {i} list was {pul.get(i)}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.