【问题标题】:Calling variables from a return function in another function but the variable in the first return changes从另一个函数中的返回函数调用变量,但第一个返回中的变量发生变化
【发布时间】:2020-12-01 12:56:47
【问题描述】:

我有一款游戏,它使用 21 和 27 数字作为其核心价值。我在函数 num_ofNum 中使用 21 作为默认参数,但是在我的主 python 文件中调用这些函数来玩我覆盖的游戏 num_ofNumbs = 21,其中 num_ofNumbs = 27。

变量 number_pool 只是一个随机的数字列表,可以在 deal_the_numbers 函数中进行索引和处理。

def deal_the_numbers(Number_Pool, num_ofNumbs = 21): 


    math = (num_ofNumbs//3)
    print(math)
    
    
    a, b, c = (Number_Pool[::3]), Number_Pool[1::3], Number_Pool[2::3]
    a = a[0:math]
    b = b[0:math]
    c = c[0:math]
    split_number_list=(a,b,c)
    print(split_number_list)
    

 
    return split_number_list

在这里,我希望列表中的前 7 个或 9 个数字分别成为 b 或 c 值。 This works as desired in this function as the math variable prints 9 when a game of 27 is chosen.

output: 9

split_number_list 然后也根据需要返回

(['92', '45', '61', '88', '78', '66', '32', '12', '1'], ['99', '76', '71', '61', '90', '10', '44', '77', '13'], ['8', '4', '89', '98', '21, '65', '5', '14', '19'])

但是,当我在另一个函数中调用此变量时,它并没有按照我的意愿返回前 9 个数字,而是返回列表中的 7 个数字,使游戏与 21 数字游戏相同。

def combine_num(split_number_list,card_column):


    s = def deal_the_numbers(Number_Pool)
    a,b,c = s
    print("")
    print("cards being dealt")
    print(s)

但是,当调用此函数并将其返回变量定义为“s”时,曾经打印 9 的 deal_the_numbers 函数中的同一打印行现在打印 7。变量“s”还打印七个数字三个列表中的每一个,而不是所需的 9 个。

output: (['92', '45', '61', '88', '78', '66', '32'], ['99', '76', '71', '61', '90', '10', '44'], ['8', '4', '89', '98', '21, '65', '5'])

我的主要想法是使用可以在我的主要 python 文件中覆盖的默认参数,以便 num_ofnums = 27 并且我可以使用 27 和 21 数字玩游戏。任何想法。

【问题讨论】:

  • 如果我理解正确:提供参数时,函数定义中不会替换默认参数。每个呼叫都是新的,因此 21 仍将是默认值。您应该有一个 21 或 27 的变量,并在函数调用中使用
  • 感谢您的回复,是的,所以当变量被传递时,如果我理解正确的话,它不能被替换为我想要放置的参数

标签: python list function return


【解决方案1】:

很难对您想要在这里实现的目标进行逆向工程 - 下一次,请尝试稍微隔离问题(可以想象的最简单的业务场景)。不过,我会试一试:

s = def deal_the_numbers(Number_Pool)

def 用于实际定义一个函数,而不是调用它。如果你想调用 num_ofNumbs = 27 的函数,只需将它传递给函数:

s = deal_the_numbers(Number_Pool, 27)

如果省略第二个参数,将使用默认值 (21)。

这里有很多解释:https://www.w3schools.com/python/python_functions.asp

【讨论】:

    猜你喜欢
    • 2013-02-28
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    相关资源
    最近更新 更多