You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何在两个函数间传递变量/字典且不使用全局变量

实现方案

核心逻辑是利用函数返回值传递生成的字典,完全不需要依赖全局变量,修改步骤如下:

  • 删掉全局作用域的dictionary = dict()初始化语句
  • 在fileProcessing函数内部初始化空字典,处理完成后用return返回这个字典
  • 调用fileProcessing时用变量接收返回的字典,再将该变量作为参数传入swappingKandV_PrintingResults

另外注意你原代码里line.rstrip()、line.split()两行没有赋值给变量,属于无效代码,下面是完整修改后的可运行代码:

fileinputname = input("Please Input File Name: ")
try:
    filehandling = open(fileinputname)
except:
     print("Invalid Entry")
     quit()

rawfile = filehandling.readlines()

def fileProcessing(rawfile):
    # 函数内部初始化字典,不使用全局变量
    dictionary = dict()
    for iteration in(range(len(rawfile))):
        rawfile[iteration] = rawfile[iteration].lower()
    for line in rawfile:
        # 修复原无效代码,赋值处理后的字符串
        line = line.rstrip()
        for words in line:
            if words.isalpha():
                dictionary[words] = dictionary.get(words, 0) + 1
    # 返回生成的字典
    return dictionary

def swappingKandV_PrintingResults(dictionary):
    finalresults = []
    for (k,v) in dictionary.items():
        newtuple = (v, k)
        finalresults.append(newtuple)
    finalresults = sorted(finalresults, reverse=True)
    for iteration in finalresults:
        print(iteration)

# 接收fileProcessing返回的字典,再传入下一个函数
processed_dict = fileProcessing(rawfile)
swappingKandV_PrintingResults(processed_dict)

内容的提问来源于stack exchange,提问作者TooMuch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:45:03