python - 将 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)
解决方案
roll_counts
inshow_roll_data(roll_counts)
是参数的名称,可在整个show_roll_data
函数范围内访问。它的值是在roll_data
调用中传入的show_roll_data(roll_data)
,与中定义的同名局部变量无关simulate_dice_rolls
。这就是为什么你可以重命名roll_counts
为show_roll_data
任何东西,它仍然可以工作。
推荐阅读
- javascript - 提交名称时,我正在尝试更改我的跨度标签
- css - CSS:如何选择一个元素是其中一个祖先(不是直接父)的第一个类型?
- c++ - 具有第二种模板类型的部分模板特化
- python - 为 Discord 排行榜排序 JSON 文件
- python - 如何在 Python 中生成月份名称作为列表?
- ffmpeg - 当多个循环输入缓冲区中的任何一个溢出时如何使ffmpeg失败
- amazon-web-services - nginx 入口控制器显示在 AWS EKS 中运行,但运行状况检查显示 OutOfService
- function - Go - exec.Command() 但对于字符串切片
- api - 工件 REST API 归档条目列表
- python - 如何加密和解密电子邮件地址以匿名数据