简体   繁体   English

将return作为参数传递给另一个函数

[英]Pass return as parameter for another function

In the below code "roll_counts" has been used as a return for the first function and then as a parameter for the second function. 在下面的代码中,“ roll_counts”已用作第一个函数的返回值,然后用作第二个函数的参数。 my question is if I change roll_counts in second function's parameter to ABC and leave it roll_counts in the first function, the code will still work fine. 我的问题是,如果我将第二个函数的参数roll_counts更改为ABC并将其roll_counts保留在第一个函数中,代码仍然可以正常工作。 i know roll_counts = 6 in parentheses but how? 我知道圆括号中的roll_counts = 6,但是如何? and why the result doesn't change when ii am new to python and programming, thanks in advance 以及为什么ii是python和编程新手时结果不会改变,请提前感谢

import random as rd

def simulate_dice_rolls(N):
    roll_counts = [0,0,0,0,0,0]
    for i in range(N):
        roll = rd.choice([1,2,3,4,5,6])
        index = roll - 1
        roll_counts[index] = roll_counts[index] + 1
    return roll_counts

def show_roll_data(roll_counts):
    number_of_sides_on_die = len(roll_counts)
    for i in range(number_of_sides_on_die):
        number_of_rolls = roll_counts[i]
        number_on_die = i+1
        print(number_on_die, "came up", number_of_rolls, "times")

roll_data = simulate_dice_rolls(1000)
show_roll_data(roll_data)

roll_counts in show_roll_data(roll_counts) is the name of a parameter and is accessible throughout the scope of the show_roll_data function. roll_countsshow_roll_data(roll_counts)是一个参数的名称,在整个范围访问show_roll_data功能。 Its value is passed in from roll_data in the call show_roll_data(roll_data) , and has nothing to do with the local variable of the same name defined in simulate_dice_rolls . 它的值是从传递roll_data呼叫show_roll_data(roll_data)并有无关的定义相同名称的局部变量simulate_dice_rolls That's why you can rename roll_counts in show_roll_data to anything and it would still work. 这就是为什么您可以将show_roll_data roll_counts重命名为任何内容,并且仍然可以使用的原因。

blhsing 's answer is right. blhsing的答案是正确的。 But before admitting that answer, you need to understand variable scope. 但是在接受该答案之前,您需要了解变量范围。 There are global variables and local variables in python. python中有全局变量和局部变量。 And local variables are binded in functions. 并且局部变量绑定在函数中。 If there is same local variable to global variable in function, local variable is used without affection of global variable. 如果函数中的全局变量与局部变量相同,则使用局部变量而不会影响全局变量。 Because roll_counts is local variable of simulate_dice_rolls, you don't need to consider roll_counts in show_roll_data. 由于roll_counts是simulate_dice_rolls的局部变量,因此您无需在show_roll_data中考虑roll_counts。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM