![](/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.