繁体   English   中英

尝试使用变量从列表中删除项目

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM