簡體   English   中英

您如何從列表中獲取值並將其分配給變量

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

只是想知道如何從滾動列表中獲取一個值並將其分配給一個變量,以便在其余代碼中使用。

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)

已死@ user3119844。

我認為您的問題有點奇怪,因為它與當前的代碼不一致。

通過代碼,您似乎是一位相當熟練的python程序員。 因此,要么我不了解這個問題,要么這很奇怪。

即使在我看來,rolls字典也包含3個列表(與3個不同的骰子有關),每個列表都包含一些值。 在python中,您可以使用[](括號)通過其索引訪問值。 因此,選擇一個變量名,例如說v ,然后:

v=rolls[diceNumber][rollIndex]

其中diceNumber是4,6或12,而rollIndex是您感興趣的第n個卷的編號。

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM