未在Python中定义全局名称maxLengthPOI

2024-10-04 07:36:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解Python中全局变量的这种奇怪行为

我想简单解释一下代码: 这里有一个函数populate\u sheet,它比较两个不同dataframe中的同一列,并返回另一个具有不常见记录的dataframe。你知道吗

下一步,如果列名是u'Lead-programmeofinterest'。我想根据modifyPoI\u 0函数对列进行处理,该函数返回元组的第一个元素。你知道吗

这里是问题所在,我定义了一个变量maxLengthPOI,并使其成为全局变量,这样它就包含了u'Lead-programmeofinterest'列中元组的最大长度

运行此代码会出现错误:未定义全局名称maxlengthPOI

def populate_sheet(df, input, output, sheet_name, sheet, columnName, sheetInputIndex, sheetOutputIndex ):

    differentPosition = pd.notnull(output[columnName]) & (input[columnName] != output[columnName])  

    df = pd.DataFrame(columns = [sheet[sheetInputIndex], sheet[sheetOutputIndex]] )
    df[sheet[sheetInputIndex]] = pd.Series(input.loc[differentPosition, columnName])    
    df[sheet[sheetOutputIndex]] = pd.Series(output.loc[differentPosition, columnName])   

    if columnName == u'Lead-Programme of interest':
    #Identify the max length of the tuple : maxLengthPOI 
    #THROWS ERROR: Global name maxLengthPOI is not defined.
        maxLengthPOI = 1  
        def modifyPoI_0(value):
            global maxLengthPOI
            if type(value) == tuple:
                if maxLengthPOI < len(value):
                    maxLengthPOI = len(value)
                return value[0]
            else:
                return value

        df[sheet[sheetOutputIndex]] = df[sheet[sheetOutputIndex]].apply(modifyPoI_0)  

    output.loc[differentPosition, columnName] = [ '=' + sheet_name + '!' + xl_rowcol_to_cell(i+1,sheetOutputIndex ) 
                                           for i in range(sum(differentPosition))]

    return df

但是当我运行一个简单的脚本

ser = pd.Series([(1, 2), (3, 4, 5, 6), 1, 2])
maxLengthPOI = 1      
def modifyPoI_0(value):
    global maxLengthPOI
        #basically in LeadPoI if its a tuple then return the 
    if type(value) == tuple:
        if maxLengthPOI < len(value):
            maxLengthPOI = len(value)
            return value[0]
        else:
            return value
ser.apply(modifyPoI_0)

正确地给出输出

0          (1, 2)
1    (3, 4, 5, 6)
2            None
3            None
and maxLengthPOI = 4

为什么我们会有这种奇怪的行为,在第一种情况下,它抛出一个错误,在第二种情况下,相同的代码正常工作,正如预期的那样


Tags: 代码dfoutputlenreturnifvaluesheet
2条回答

当你打电话的时候

#THROWS ERROR: Global name maxLengthPOI is not defined.
        def modifyPoI_0(value):
            global maxLengthPOI

maxLengthPOI不存在。你知道吗

正如您在发布的第一个代码中所看到的,maxLengthPOI不是位于外部defglobal。因此,当您调用modifyPoI_0时,它不存在,因为它无法从populate_sheet中退出。把它global也放在那里,就不会有问题了。你知道吗

global的内容可以被认为是:如果不定义global并且在函数内更改变量,那么值不会全局更改,它只会在函数内更改。你知道吗

考虑一下:

x = 2
print(x)
def func():
    x = 4
    print(x)
func()
print(x)

print('  ')

x = 2
print(x)
def func2():
    global x
    x = 4
    print(x)
func2()
print(x)

这张照片:

2
4
2
# See? x haven't changed, even i called a function which changes its value (It actually changed inside the function as you can see, but not globally)
  
2
4
4
# Now x changed, because i made the variable global, so it 'got out' of the function after its change
def populate_sheet(df, input, output, sheet_name, sheet, columnName, 
    maxLengthPOI = 1  # defined in populate_sheet() so local to populate_sheet(), not global!
    def modifyPoI_0(value):
        global maxLengthPOI # not defined (as a global)

在任何函数外定义maxLengthPOI,将其用作全局变量。或者最好:尽量避免使用全局参数,而使用额外的参数(可能大多数时候)。你知道吗

相关问题 更多 >