[英]Trying to remove an item from a list using a variable
做了一個猜數字游戲,根據程序創建的隨機數自動更新事實列表。 如果用戶猜錯了,程序會從列表中提供提示。 我希望程序在使用后從列表中刪除此提示,因此沒有重復項。
我嘗試將 X 分配為列表的隨機數,然后使用相同的 X 變量將該事實從列表中彈出。 .pop 當然不喜歡這樣。
while counter <= 4 and guess != num_final:
guess = input("Guess your " + grammar_list[int(counter)] + "number: ")
Dif: int = (abs((num_final - int(guess))))
if (int(num_final) == int(guess)):
break
elif int(Dif) >= 10:
print("Your guess was over 10 numbers away. Here's a hint.")
time.sleep(1.5)
x = random.choice
print(x(facts_list))
facts_list.pop(x)
elif int(Dif) <= 10:
print("Your guess is within 10 digits of the computer's number. Here's a hint.")
time.sleep(1.5)
x = random.choice
print(x(facts_list))
facts_list.pop(x)
counter = counter + 1
給出提示后,如何從列表中刪除該事實?
function random.choice
不返回隨機數,它從您作為參數傳遞的序列中返回一個隨機值。 您正在設置x = random.choice
,這意味着x
現在是 function random.choice
,因此將其傳遞給pop()
function 將引發錯誤,因為它期望一個int
參數作為您想要pop()
的項目的索引.
如果你想使用pop()
刪除一個項目,你應該更改為這樣的:
x = random.randrange(len(facts_list))
print(facts_list[x])
facts_list.pop(x)
random.randrange(len(facts_list))
將生成一個從 0 到len(facts_list)
的隨機 integer
然后它將使用x
的值作為索引打印項目,然后彈出該索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.