如何将range(5)范围内的值赋值给变量?

2024-06-02 06:39:44 发布

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

所以我在用python做一个yahtzee游戏。我把它设置成当你按按钮时掷骰子。然后你可以通过点击它来阻止数字再次滚动。我的目标是将这个范围(5)中的值赋给一个变量。我希望每次单击骰子按钮时都能更新变量。你知道吗

这只是一个游戏,我一直在为自己的工作,以更好地与python。我试着想办法把它分配给一个dict,但我一直找不到办法。你知道吗

from tkinter import *
from random import randint

root = Tk()
root.title("Sam's Yahtzee")

def roll(dice, times):
    if times > 0:
        dice['text'] = randint(1, 6)
        root.after(10, roll, dice, times-1)

def roll_dices():
    for i in range(5):
        if dices[i][1].get() == 0:
            # dice is not held, so roll it
            roll(dices[i][0], 10)

dices = []
for i in range(5):
    ivar = IntVar()
    dice = Checkbutton(root, text=randint(1, 6), variable=ivar, bg='silver', bd=1, font=('Arial', 24), indicatoron=False, height=3, width=5)
    dice.grid(row=0, column=i)
    dices.append([dice, ivar])

Button(text='Dice', command=roll_dices, height=2, font=(None, 16, 'bold')).grid(row=1, column=0, columnspan=5, sticky='ew')

yahtzee = 0
threeKind = 0
fourKind = 0
fullHouse = 0
smallStraight = 0
largeStraight = 0
chance = 0

possibleHands = {"yahtzee": yahtzee,
                 "threeKind": threeKind,
                 "fourKind": fourKind,
                 "fullHouse": fullHouse,
                 "smallStraight": smallStraight,
                 "largeStraight": largeStraight,
                 "chance": chance}

root.mainloop()

Tags: textrootdicerollrandinttimeschanceyahtzee
3条回答

这就是你想要的吗?你知道吗

nums = list(range(5)) #nums is now list of [0,1,2,3,4]

另一种方式,除了list(range(5))

nums = [*range(5)]
print(nums)

# [0, 1, 2, 3, 4]

好像也快了不少。(我使用100进行更精确的测试。)

In [1]: %timeit nums = list(range(100))
3.24 µs ± 87.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [2]: %timeit nums = [*range(100)]
1.08 µs ± 40.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

I understand this, but is there a way for me to get a list of the same numbers from the for loop?

我猜您只希望语句块执行n(=1000)次,每次都使用名为num的相同数字。如果是,您可以使用:

n = 1000
num = 1 # the number you want to repeat
#Execute for 0.06280231475830078s
for i in [num]*n: 
    print(i)

或者

n = 1000
num = 1 # the number you want to repeat
#Execute for 0.05784440040588379s
for _ in range(n):
    print(num)

相关问题 更多 >