如何计算function_1中的局部变量并将结果发送到function_2,而不需要每次调用function_2时都运行function_1?

问题描述 投票:0回答:4

我正在尝试设计一款具有“洗牌”功能和“发牌”功能的纸牌游戏。我遇到的问题是,每次我将“洗牌”的结果传递给“发牌”时,牌都会被洗牌。我是局部变量的新手...当我只想计算一次“洗牌”效果时,如何将局部变量从“洗牌”传递到“交易”?

这是我尝试过的简化示例:

import random

def shuffle():
    x = random.randrange(1, 11)
    return x

def deal():
    x = shuffle()
    print('\nx =', x)
    inpt = input('\nEnter anything to deal again, or x to quit: ')
    if inpt == 'x':
        quit()

while True:
    deal()

我希望“deal”打印出一致的 x 值,但每次迭代都会对其进行打乱。如何将 x 打乱一次,以便将 x 打印为一致的值?

*注意:我知道我可以通过使其只是一个函数来简化这段代码,但我需要帮助理解局部变量如何在函数之间移动。谢谢

python local-variables
4个回答
0
投票

您可以做到的一种方法是首先修改

deal()
以接受某些参数,假设它称为
shuffle_value
,它将代替示例代码中的
x
。然后为一些全局变量分配一个来自
shuffle()
的值,然后将其传递到
deal
函数中。这样,
shuffle
仅在全局范围内调用一次,这将在
deal
的所有调用中保持值一致。

如果这有点令人困惑,这里是实际的代码:

import random

def shuffle():
    x = random.randrange(1, 11)
    return x

def deal(shuffle_value): # takes in an argument "shuffle_value"
    print('\nx =', shuffle_value) # notice that shuffle_value took the place of x
    inpt = input('\nEnter anything to deal again, or x to quit: ')
    if inpt == 'x':
        quit()

shuffle_value = shuffle() # global variable which is assigned a value from shuffle()

while True:
    deal(shuffle_value) # pass in the global variable "shuffle_value"

0
投票

您的示例的问题是您可以多次抽同一张牌(整数):

x = random.randrange(1, 11)

不随机播放,而是从一定范围内随机抽取。

虽然你似乎想洗牌,然后从中抽牌来发牌。

这是一个关于如何从 52 副牌中向 2 位玩家发 7 张牌的简单示例。

import numpy as np

创建牌组并空手:

deck = list(range(52))
hands = [[], []]

就地洗牌

def shuffle(deck):
    np.random.shuffle(deck)

从牌组发牌到手牌:

def deal(deck, hands, n=7):
    for _ in range(n):
        for i in range(len(hands)):
            hands[i].append(deck.pop())

然后我们调用这个过程:

shuffle(deck)
deal(deck, hands)

结果:

hands
#[[3, 12, 33, 46, 21, 18, 42], [19, 30, 16, 25, 23, 28, 20]]

len(deck)
# 38 = 52 - 14

0
投票

这是因为你在 deal 方法中调用了 shuffle。像这样的东西应该会给你你正在寻找的东西。

import random

def shuffle():
    x = random.randrange(1, 11)
    return x

def deal(x):
    # x = shuffle()
    print('\nx =', x)
    inpt = input('\nEnter anything to deal again, or x to quit: ')
    if inpt == 'x':
        quit()

x = shuffle()

while True:
    deal(x)

或者,您可以将 while True: 移至 deal 方法中。

import random

def shuffle():
    x = random.randrange(1, 11)
    return x

def deal():
    x = shuffle()
    while True:
        print('\nx =', x)
        inpt = input('\nEnter anything to deal again, or x to quit: ')
        if inpt == 'x':
            quit()

deal()

0
投票

使用 functools.cache

这样,shuffle()函数将始终返回相同的(原始)值。

import random
from functools import cache

@cache
def shuffle():
    x = random.randrange(1, 11)
    return x

def deal():
    x = shuffle()
    print('\nx =', x)
    inpt = input('\nEnter anything to deal again, or x to quit: ')
    if inpt == 'x':
        quit()

while True:
    deal()

随后,如果您希望 shuffle() 返回一个(可能)新值,只需调用 shuffle.cache_clear()

© www.soinside.com 2019 - 2024. All rights reserved.