int()参数必须是字符串或数字

时间:2013-11-14 04:04:22

标签: python list int

我收到了一个错误。我做了快速谷歌搜索,这对我没有帮助。

我添加了整个代码,很好的整个代码。来自用户的请求。

from derp_node import *

##############################################################################
# parse
############################################################################## 

def parse(tokens, i = 0):
    """parse: tuple(String) * int -> (Node, int)
    From an infix stream of tokens, and the current index into the
    token stream, construct and return the tree, as a collection of Nodes, 
    that represent the expression.

    NOTE:  YOU ARE NOT ALLOWED TO MUTATE 'tokens' (e.g. pop())!!!  YOU
        MUST USE 'i' TO GET THE CURRENT TOKEN OUT OF 'tokens'
    """
    if tokens == []:
        raise TypeError("Error: Empty List.")
    elif tokens[int(i)] == '*':
        tokens.remove(int(i))
        return mkMultiplyNode(parse(tokens), parse(tokens))
    elif tokens[int(i)] == '//':
        tokens.remove(int(i))
        return mkDivideNode(parse(tokens), parse(tokens))
    elif tokens[int(i)] == '+':
        tokens.remove(int(i))
        return mkAddNode(parse(tokens), parse(tokens))
    elif tokens[int(i)] == '-':
        tokens.remove(int(i))
        return mkSubtractNode(parse(tokens), parse(tokens))
    elif tokens[int(i)].isdigit():
        return mkLiteralNode(tokens.remove(int(i)))
    elif not tokens[int(i)].isdigit():
        return mkVariableNode(tokens.remove(int(i)))
    else:
        raise TypeError("Error: Invalid Input")

##############################################################################
# main
##############################################################################

def main():
    """main: None -> None
    The main program prompts for the symbol table file, and a prefix 
    expression.  It produces the infix expression, and the integer result of
    evaluating the expression"""

    print("Hello Herp, welcome to Derp v1.0 :)")

    inFile = input("Herp, enter symbol table file: ")
    symTbl = {}
    for line in open(inFile):
        i = line.split()
        symTbl[i[0]] = int(i[1])
    print("Derping the symbol table (variable name => integer value)...")
    for variable in sorted(symTbl):
        print(variable + " => " + str(symTbl[variable]))

    # STUDENT: CONSTRUCT AND DISPLAY THE SYMBOL TABLE HERE

    print("Herp, enter prefix expressions, e.g.: + 10 20 (RETURN to quit)...")

    # input loop prompts for prefix expressions and produces infix version
    # along with its evaluation
    while True:
        prefixExp = input("derp> ")
        if prefixExp == "":
            break

        # STUDENT: GENERATE A LIST OF TOKENS FROM THE PREFIX EXPRESSION
        prefixLst = prefixExp.split()
        # STUDENT: CALL parse WITH THE LIST OF TOKENS AND SAVE THE ROOT OF 
        # THE PARSE TREE.
        tokens = []
        parseLst = parse(prefixLst, tokens)
        # STUDENT: GENERATE THE INFIX EXPRESSION BY CALLING infix AND SAVING
        # THE STRING    
        infixLst = infix(parseLst)

        print("Derping the infix expression:")

        # STUDENT: EVALUTE THE PARSE TREE BY CALLING evaluate AND SAVING THE
        # INTEGER RESULT

        print("Derping the evaluation:")

    print("Goodbye Herp :(")

if __name__ == "__main__":
    main()

我收到的错误是:

  File "derpNew.py", line 31, in parse
    if tokens[int(i)] == '*':
TypeError: int() argument must be a string or a number, not 'list'

如果我从变量i中删除int(),那么我会收到此错误:TypeError: list indices must be integers, not list

我想将列表转换为元组吗?任何帮助都会很棒。谢谢。

如果你们好奇我是如何调用解析的。我把它放在主要功能下。

    tokens = []
    parseLst = parse(tokens, i)

修改 循环:

while True:
    prefixExp = input("derp> ")
    if prefixExp == "":
        break
    prefixLst = prefixExp.split()
    tokens = []
    parseLst = parse(tokens, i)

3 个答案:

答案 0 :(得分:1)

parseLst = parse(tokens, i) - 除非您定义i,否则此行没有意义。如果您想通过默认i=0,请将其保留:parseLst = parse(tokens)

编辑:在粘贴完整个代码之后,之前定义了一些(显然无关的)i,这就是为什么没有NameError。

答案 1 :(得分:0)

传递的变量ilist,这就是错误的原因!需要更多关于传递的参数的信息来帮助你更多!

列表索引就像这样工作

>>> my_list = [1, 2, 3, 4, 5]
>>> for index in range(5):
...    print my_list[i]
1
2
3 
4
5
>>> my_list[3]
4

答案 2 :(得分:0)

您将哪些方法作为第二参数传递给方法parse(...)?如果它是一个列表,它不应该。您可能希望将要传递的值更改为parse

您可能还想在另一个tokens之前检查ifs是否为空列表,否则会导致其他错误。

if tokens == []:
    raise TypeError("Error: Empty List.")
elif tokens[int(i)] == '*':
    tokens.remove(int(i))
    return mkMultiplyNode(parse(tokens), parse(tokens))
    return mkSubtractNode(parse(tokens), parse(tokens))
elif tokens[int(i)].isdigit():
    return mkLiteralNode(tokens.remove(int(i)))
elif not tokens[int(i)].isdigit():
    return mkVariableNode(tokens.remove(int(i)))
else:
    raise TypeError("Error: Invalid Input")