简体   繁体   中英

How would you take a value from a list and assign it to a variable

Just wondering how I could take a value from the list in rolls and assign it to a variable to use within the rest of my code.

import random

def dice_roll(number):
    if number == 12:
        number = random.randint(1,12)
        print(number)
        return number
    elif number == 6:
        number = random.randint(1,6)
        print(number)
        return number
    else:
        number == 4
        number = random.randint(1,4)
        print(number)
        return number

print("12 sided")
print("6 sided")
print("4 sided")

rolls = {4: [], 6: [], 12: []} # dictionary to hold rolls
while True:
    roll = int(input("Which dice would you like to roll? --> ")) # store die size
    rolls[roll].append(dice_roll(roll)) # roll and add to dictionary
    doRepeat=input("Go again? --> ")
    if doRepeat == "no":
        break 
    print(rolls)

Dead @user3119844.

I think your question was a little weird since it is not coherent with the code present.

By the code you seem to be a fairly skilled python programmer. So either I haven't understood the question or it is just weird.

Even though, it seems to me the the rolls dictionary holds 3 lists (related to 3 different dices) and each list holds a few values. In python you use [ ]'s (brackets) to access values by its index. So pick up a variable name, say v for instance, then:

v=rolls[diceNumber][rollIndex]

where diceNumber is either 4,6 or 12 and rollIndex is the number of the nth roll you're interested in.

Hope it helps

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