简体   繁体   中英

Trying to remove an item from a list using a variable

Made a number guessing game, automatically updates a list of facts based off the random number the program creates. If user guesses incorrectly, the program offers a hint from the list. I want the program to remove this hint from the list after it is used, so there are no duplicates.

I tried to assign X as a random number, for the list, then use the same X variable to pop that fact out of the list. .pop, of course, doesn't like that.

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

How can I remove the fact from the list after I give the hint?

The function random.choice does not return a random number, it returns a random value from the sequence you pass as an argument. You are setting x = random.choice , meaning x is now the function random.choice so passing that to the pop() function will throw an error as that is expecting an int argument as the index of the item you want to pop() .

If you want to remove an item using pop() you should change to something like this:

x = random.randrange(len(facts_list))
print(facts_list[x])
facts_list.pop(x)

random.randrange(len(facts_list)) will generate a random integer from 0 to len(facts_list)

Then it will print the item using the value of x as an index, and then pop that index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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