【问题标题】:How could I assign the values from range(5) to a variable?如何将 range(5) 中的值分配给变量?
【发布时间】:2019-06-06 22:01:03
【问题描述】:

所以我正在用 python 制作一个 yahtzee 游戏。当您单击按钮时,我已设置为掷骰子。然后,您可以通过单击它来阻止该数字再次滚动。我的目标是将此范围(5)中的值分配给一个变量。最好我希望每次单击骰子按钮时它都会更新变量。

这只是为了我一直在为自己开发的一款游戏,以便更好地使用 python。我试图想办法将它分配给一个字典,但我一直无法找出如何。

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()

【问题讨论】:

  • 请更具体地说明您的目标是什么。您希望变量中 0-4 的数字作为列表吗?
  • 另一个非常similar questionHere's a third.
  • range() 是 python 3 中的生成器,因此您需要调用 list(range(5))[*range(5)]
  • @Poojan 我希望从 CheckButton 中的 randint(1, 6) 获取相同的数字到变量中。编辑:但我仍然希望数字出现在窗口中

标签: python


【解决方案1】:

这是你想要的吗?

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

【讨论】:

  • 我明白这一点,但有没有办法让我从 for 循环中获取相同数字的列表?
【解决方案2】:

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)

【讨论】:

    【解决方案3】:

    我明白这一点,但有没有办法让我得到一个相同的列表 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)
    

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

    【讨论】:

    • @Sam 对你的问题有用吗:I understand this, but is there a way for me to get a list of the same numbers from the for loop?
    猜你喜欢
    • 1970-01-01
    • 2021-03-10
    • 2021-09-17
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 2010-11-13
    相关资源
    最近更新 更多