使用def函数和保存变量的问题

时间:2015-10-08 03:21:39

标签: python store function

我想使用以下函数存储 all_tmp all_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)不会存储。我错了吗?

3 个答案:

答案 0 :(得分:0)

保存变量或仅return' em?

最初提出的 tempDat = return ( aTupleOfVALUEs ) 概念
失败
tempDat 必须已在适当的位置声明为 global ,以便能够从return内部生存def(): global -ed代码的代码范围范围仍然保持" 可见" /" 可访问" return aTupleOfVALUEs # or any other representation of the results / data - ly(哪种做法虽然可行,但并不总是被认为是一种好的设计

对于大多数情况,只需使用

返回值即可
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 )

提示使用python上下文:

mysql_query(): Unknown column 'steamprofile' in 'field list' on line 9

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

答案 1 :(得分:0)

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

这样的事情:

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

答案 2 :(得分:-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