我很难理解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
为什么我们会有这种奇怪的行为,在第一种情况下,它抛出一个错误,在第二种情况下,相同的代码正常工作,正如预期的那样
当你打电话的时候
maxLengthPOI
不存在。你知道吗正如您在发布的第一个代码中所看到的,
maxLengthPOI
不是位于外部def
的global
。因此,当您调用modifyPoI_0
时,它不存在,因为它无法从populate_sheet
中退出。把它global
也放在那里,就不会有问题了。你知道吗global
的内容可以被认为是:如果不定义global
并且在函数内更改变量,那么值不会全局更改,它只会在函数内更改。你知道吗考虑一下:
这张照片:
在任何函数外定义
maxLengthPOI
,将其用作全局变量。或者最好:尽量避免使用全局参数,而使用额外的参数(可能大多数时候)。你知道吗相关问题 更多 >
编程相关推荐