【问题标题】:Problems with using def function and saving variables使用 def 函数和保存变量的问题
【发布时间】:2016-01-05 12:00:42
【问题描述】:

我想做下面的函数来存储all_tmpall_date数据并在以后使用。这就是我所拥有的......

def temperature(temp_file):
    '''
    This is a function that loads temperature data
    from WeatherUnderground. Type in the following:
    temperature('filename.filetype')
    '''

    file_obj=open(temp_file)

    all_dates=[]
    all_tmps=[]

    for line in file_obj:
        words=line.split(',')
        try:
            dates=parse(words[0])
            tmps=float(words[1])
            all_dates.append(dates)
            all_tmps.append(tmps)   
        except (ValueError,IndexError):
            pass

    file_obj.close()

    tempDat= return(all_dates,all_tmps) # This is supposed to store the variables...

(all_dates,all_tmps) = temperature(temp_file)

我想在单独的脚本中打开我的每个函数并绘制它们...但是我的变量(all_datesall_tmps)不会存储。我是不是缩进错了?

【问题讨论】:

  • 我不清楚你到底在问什么。你知道如何import 一个模块吗?这似乎是第一个开始的地方。
  • @Blckknght... 我改变了我需要做的事情。我的第一个障碍是让我的变量实际存储。我不知道存储它们需要什么语法。我读过其他帖子,但都没有那么有用。
  • tempDat= return(all_dates,all_tmps) 有什么用?您收到无效的语法消息吗?。
  • 我没有得到无效的语法......这是我保存变量的许多绝望尝试之一。我认为这是错误的。

标签: python store function


【解决方案1】:

首先应该是file_obj=open(temp_file, 'r') 然后你需要file = file_obj=open.read() 从文件中获取数据。你只打开它

'r' 表示只读取文件,'w' 表示只写入(已存在的同名文件将被删除),'a' 打开文件进行追加;写入文件的任何数据都会自动添加到末尾。 'r+' 打开文件进行读写。 mode 参数是可选的;如果省略,将假定为 'r'。

来自https://docs.python.org/2/tutorial/inputoutput.html

【讨论】:

  • 您可以遍历打开的文件对象以读取其中的行。
  • 啊对。我说错了语言。对此感到抱歉
【解决方案2】:

保存变量还是只保存return 'em?

最初提出的tempDat = return ( aTupleOfVALUEs )概念
fails
tempDat 必须已经在适当的地方声明为 global 以便从内部生存 return def():-ed 代码的代码范围范围内,仍然保持“可见”/“可访问global-ly( 哪种做法虽然可行,但并不总是被认为是好的设计)

大多数情况下使用简单的返回值应该没问题

return aTupleOfVALUEs         # or any other representation of the results / data

使用 python 上下文的提示:

def temperature( temp_file ):
    '''
            This is a function that loads temperature data
            from WeatherUnderground. Type in the following:
            temperature( 'filename.filetype' )
    '''
    all_dates = []
    all_tmps  = []

    with open( temp_file, 'r' ) aFILE:
         for line in            aFILE:

             words = line.split(',')
             try:
                  dates = parse( words[0] )
                  tmps  = float( words[1] )

                  all_dates.append( dates )
                  all_tmps.append(  tmps  )

             except ( ValueError, IndexError ):
                  pass

    return ( all_dates, all_tmps )

对于鹰派 pythoneers,该帖子故意使用非 PEP-8 源代码格式,因为作者体验到,在学习阶段,代码可读性提高了对任务解决方案的关注并有助于习惯底层概念,而不是花精力在正式遵守排版上。希望提供帮助的原则得到尊重,以易于阅读的名义原谅非 PEP-8 样式格式。

【讨论】:

    【解决方案3】:

    您可以使用全局字典来保存值。

    类似这样的:

    Saved_values = {}
    
    def temperature(temp_file):
    
        <Code elided>
    
        Saved_values[temp_file] = (all_dates, all_tmps)
        return Saved_vales[temp_file] # replacing your return statement
    

    【讨论】:

    • 我试过了,但我仍然收到一条错误消息,提示未定义 Saved_values、all_dates 和 all_tmps。我需要多次缩进吗?还是在我关闭文件之前输入这些行?
    • 避免代码中的标签。可以从更简单的 Hello world 类型的程序开始。
    • 其实我觉得我在函数脚本中做不到我想要的。如果我将 T= temperature('FileName.csv') 放在我的第二个脚本中,日期和温度值将被保存。然后我可以输入 T[0] 或 T[1] 来访问这些值并用它们绘图。
    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 2010-11-30
    • 1970-01-01
    • 2019-08-21
    • 2022-01-07
    相关资源
    最近更新 更多