如何从列表中取出一个值并将其赋值给一个变量

2024-04-18 10:58:12 发布

您现在位置:Python中文网/ 问答频道 /正文

只是想知道如何从rolls中的列表中获取一个值,并将其赋给一个变量,以便在代码的其余部分中使用。你知道吗

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)

Tags: tonumber列表inputdictionaryreturnifrandom
1条回答
网友
1楼 · 发布于 2024-04-18 10:58:12

死亡@user3119844。你知道吗

我认为你的问题有点奇怪,因为它与当前的代码不一致。你知道吗

从代码上看,您似乎是一个相当熟练的python程序员。所以不是我不明白这个问题就是很奇怪。你知道吗

尽管如此,在我看来,rolls字典包含3个列表(与3个不同的骰子相关),每个列表包含几个值。在python中,使用[]的(括号)通过索引访问值。所以选择一个变量名,比如说v,然后:

v=rolls[diceNumber][rollIndex]

其中diceNumber是4、6或12,rollIndex是您感兴趣的第n卷的编号。你知道吗

希望有帮助

相关问题 更多 >