Python 如何将范围(5)中的值分配给变量?
所以我正在用python制作一个yahtzee游戏。我已经设置好当你点击按钮时掷骰子。然后,您可以通过单击该号码来阻止该号码再次滚动。我的目标是将这个范围(5)中的值分配给一个变量。我希望每次单击骰子按钮时都能更新变量 这只是一个游戏,我一直在努力让自己更好地使用python。我试着想办法把它分配给一个dict,但我一直找不到方法Python 如何将范围(5)中的值分配给变量?,python,Python,所以我正在用python制作一个yahtzee游戏。我已经设置好当你点击按钮时掷骰子。然后,您可以通过单击该号码来阻止该号码再次滚动。我的目标是将这个范围(5)中的值分配给一个变量。我希望每次单击骰子按钮时都能更新变量 这只是一个游戏,我一直在努力让自己更好地使用python。我试着想办法把它分配给一个dict,但我一直找不到方法 from tkinter import * from random import randint root = Tk() root.title("Sam's Yah
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()
这是你想要的吗
nums = list(range(5)) #nums is now list of [0,1,2,3,4]
另一种方式,而不是
列表(范围(5))
:
看起来速度也快了一点。(我使用100
进行更精确的测试。)
我明白这一点,但有没有办法让我得到同样的清单 来自for循环的数字 我猜您只是希望一个语句块执行
n
(=1000)次,每次都使用相同的编号num
。如果是,您可以使用:
n = 1000
num = 1 # the number you want to repeat
#Execute for 0.06280231475830078s
for i in [num]*n:
print(i)
或
请更具体地说明你的目标是什么。是否希望变量中0-4之间的数字作为列表?可能是另一个变量的重复
range()
是python 3中的一个生成器,因此您需要调用list(range(5))
或[*range(5)]
@Poojan。我希望的是从CheckButton中的randint(1,6)中获得相同的数字,并将其转换为一个变量。编辑:但我仍然希望数字显示在窗口中我明白这一点,但有没有办法从for循环中获取相同数字的列表?@Sam这对你的问题有效:我明白这一点,但有没有办法从for循环中获取相同数字的列表?
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)
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)