首页 > 解决方案 > 将 return 作为参数传递给另一个函数

问题描述

在下面的代码中,“roll_counts”被用作第一个函数的返回值,然后作为第二个函数的参数。我的问题是,如果我将第二个函数的参数中的 roll_counts 更改为 ABC 并将它的 roll_counts 保留在第一个函数中,代码仍然可以正常工作。我知道括号中的roll_counts = 6,但如何?以及为什么当我对 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)

标签: python

解决方案


roll_countsinshow_roll_data(roll_counts)是参数的名称,可在整个show_roll_data函数范围内访问。它的值是在roll_data调用中传入的show_roll_data(roll_data),与中定义的同名局部变量无关simulate_dice_rolls。这就是为什么你可以重命名roll_countsshow_roll_data任何东西,它仍然可以工作。


推荐阅读