Python 函数将空白列表作为参数而不是单个元素列表传递

Python 函数将空白列表作为参数而不是单个元素列表传递,python,function,functional-programming,Python,Function,Functional Programming,我正在编写一个函数,它将字符串解析为列表,供另一个函数使用。它执行的操作之一是在特定递归深度(由名为lvl的变量定义的深度)将字符附加到(有时是深度递归的)列表中的字符串。这个操作,一个名为listSurgery的函数,应该用一个索引列表调用,该列表指示下一个列表在上一个列表中的位置,最后一个索引告诉深层列表中要执行操作的索引,它被一个空索引列表调用,我不知道为什么。它应该被调用的列表是[-1],但调试显示它被调用的是[]。以下是代码,缩写为: def listAssign(lst,index,

我正在编写一个函数,它将字符串解析为列表,供另一个函数使用。它执行的操作之一是在特定递归深度(由名为
lvl
的变量定义的深度)将字符附加到(有时是深度递归的)列表中的字符串。这个操作,一个名为
listSurgery
的函数,应该用一个索引列表调用,该列表指示下一个列表在上一个列表中的位置,最后一个索引告诉深层列表中要执行操作的索引,它被一个空索引列表调用,我不知道为什么。它应该被调用的列表是
[-1]
,但调试显示它被调用的是
[]
。以下是代码,缩写为:

def listAssign(lst,index,item):
    """Assigns item item to list lst at index index, returns modified list."""
    lst[index] = item
    return lst

def listInsert(lst,index,item):
    """Inserts item item to list lst at index index, returns modified list."""
    print "listInsert just got called with these arguments:",lst,index,item
    if index == 'end':
        index = len(lst)
    lst.insert(index,item)
    return lst

def listSurgery(lst,indices,f,*extraArgs):
    """Performs operation f on list lst at depth at indices indices, returns modified list."""
    print "listSurgery just got called with these arguments:",lst,indices,f,extraArgs
    parent = lst
    for index in indices[:-1]:
        parent = parent[index]
    parent = f(parent,indices[-1],*extraArgs)
    return listSurgery(lst,indices[:-1],listAssign,parent)

def parseStringToList(s):
    """Takes in a user-input string, and converts it into a list to be passed into parseListToExpr."""
    # ...
    l = [] # List to build from string; built by serially appending stuff as it comes up
    b = True # Bool for whether the parser is experiencing spaces (supposed to be True if last character processed was a space)
    t = False # Bool for whether the parser is experiencing a string of non-alphanumeric characters (supposed to be True if last character was a non-alphanumeric character)
    lvl = 0 # Keeps track of depth at which operations are supposed to be occurring
    for c in s:
        if c == ' ': # If c is a space, ignore it but send signal to break off any strings currently being written to
            b = True
        # Some elifs for c being non alphanumeric
        else: # If c is alphanumeric, append it to the string it's working on
            print c,"got passed as an alphanumeric; lvl is",lvl
            assert c.isalnum()
            if b or t: # If the string it's working on isn't alphanumeric or doesn't exist, append a new string
                l = listSurgery(l,[-1]*lvl + ['end'],listInsert,'')
                b, t = False, False
            l = listSurgery(l,[-1]*(lvl+1),lambda x,y,z:listAssign(x,y,x[y]+z),c)
        print l
    return l

while op != 'exit' and op != 'quit': # Keep a REPL unless the user types "exit" or "quit", in which case exit
    op = raw_input("> ")
    if op == 'help':
        pass # Print help stuff
    elif op in {'quit','exit'}:
        pass
    else:
        print str(parseStringToList(op))
我用
python-tt code.py
调用代码并键入
1+1=2
,得到的结果如下:

> 1+1=2
1 got passed as an alphanumeric; lvl is 0
listSurgery just got called with these arguments: [] ['end'] <function listInsert at 0x10e9d16e0> ('',)
listInsert just got called with these arguments: [] end 
listSurgery just got called with these arguments: [''] [] <function listAssign at 0x10e9d10c8> ([''],)
Traceback (most recent call last):
  File "analysis.py", line 276, in <module>
    print str(parseStringToList(op))
  File "analysis.py", line 218, in parseStringToList
    l = listSurgery(l,[-1]*lvl + ['end'],listInsert,'')
  File "analysis.py", line 63, in listSurgery
    return listSurgery(lst,indices[:-1],listAssign,parent)
  File "analysis.py", line 62, in listSurgery
    parent = f(parent,indices[-1],*extraArgs)
IndexError: list index out of range
>1+1=2
1以字母数字形式通过考试;lvl为0
listSurgery刚被以下参数调用:[['end']('',)
listInsert刚被以下参数调用:[]结束
listSurgery刚刚被调用,并带有以下参数:[''][([''],)
回溯(最近一次呼叫最后一次):
文件“analysis.py”,第276行,在
打印str(parseStringToList(op))
parseStringToList中的文件“analysis.py”,第218行
l=listSurgery(l,[-1]*lvl+['end'],listInsert')
listSurgery中第63行的文件“analysis.py”
返回列表(lst,索引[:-1],列表分配,父项)
listSurgery中第62行的文件“analysis.py”
父项=f(父项,索引[-1],*extraArgs)
索引器:列表索引超出范围

有人能解释一下吗?为什么
listSurgery
得到的是
[]
而不是
[-1]
lvl
0
,此时应该传递的参数是
[-1]*(lvl+1)
。你的
lvl
是0,所以
[-1]*lvl+['end']
['end']
,而不是
'1'

你的
lvl
是0,所以
[-1]*lvl+['end']
['end']
。现在['end']是长度为1的列表,因此
['end'][:-1]
['end'][:1-1]
相同,这与
['end'][:0]
相同。这将计算为空列表。

我明白了。所以我通过改变
listSurgery
的定义来解决这个问题,如果
len(index)==1,那么在替换后只返回
lst
,对吗?(我现在无法访问我的代码,明天将更改)