简体   繁体   English

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

[英]int() argument must be a string or a number

I got an error.我有一个错误。 I did quick googling and it did not help me well.我做了快速的谷歌搜索,但对我没有帮助。

I added the whole code, well kind of whole code.我添加了整个代码,很好的整个代码。 request from a user.来自用户的请求。

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()

The error I received is:我收到的错误是:

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

If I remove the int() from the variable i , then I would get this error: TypeError: list indices must be integers, not list如果我从变量i删除 int() ,那么我会得到这个错误: TypeError: list indices must be integers, not list

Am I suppose to convert the list to tuple?我想将列表转换为元组吗? Any help would be great.任何帮助都会很棒。 Thank you.谢谢你。

If you guys are curious how I am calling the parse.如果你们很好奇我是如何调用解析的。 I put this under main function.我把它放在主函数下。

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

EDIT: The loop:编辑:循环:

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

parseLst = parse(tokens, i) - this line doesn't make sense unless you define i . parseLst = parse(tokens, i) - 除非您定义i否则此行没有意义。 If you want to pass default i=0 , then just leave it out: parseLst = parse(tokens) .如果您想传递默认i=0 ,那么只需将其省略: parseLst = parse(tokens)

EDIT: After the whole code has been pasted, there is some (apparently irrelevant) i defined before, which is why there was no NameError.编辑:粘贴整个代码后, i之前定义了一些(显然不相关),这就是没有 NameError 的原因。

The passed variable i is a list , that's why the errors!传递的变量i是一个list ,这就是错误的原因! Would need more info on the arguments being passed to help you more!需要更多关于传递的参数的信息来帮助你更多!

List indices work like this列表索引是这样工作的

>>> 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

What are you passing to the method parse(...) as second parameter?您将什么传递给方法parse(...)作为第二个参数? If it's a list, it shouldn't.如果是列表,则不应该。 You may want to change the value you are passing to parse .您可能想要更改传递给parse的值。

You may also want to check if tokens is an empty list, before the other ifs , or it will cause another error.您可能还想在其他ifs之前检查tokens是否为空列表,否则会导致另一个错误。

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 int()参数必须是字符串或数字,而不是'Choice' - int() argument must be a string or a number, not 'Choice' 为什么int()参数必须是字符串或数字,而不是'list'? - Why int() argument must be a string or a number, not 'list'? int()参数必须是字符串或数字,而不是'SimpleLazyObject' - int() argument must be a string or a number, not 'SimpleLazyObject' TypeError:int()参数必须是字符串或数字,而不是'Binary' - TypeError: int() argument must be a string or a number, not 'Binary' int() 参数必须是字符串或数字,而不是“生成器” - int() argument must be a string or a number, not 'generator' django - int参数必须是字符串或数字,而不是'元组' - django - int argument must be a string or a number, not 'Tuple' Django int()参数必须是字符串或数字 - Django int() argument must be a string or a number TypeError:int()参数必须是字符串或数字,而不是“列表” - TypeError: int() argument must be a string or a number, not 'list' int() 参数必须是字符串或数字,而不是“NoneType” - int() argument must a string or a number, not 'NoneType' int()参数必须是字符串或数字,而不是“会议” - int() argument must be a string or a number, not 'Meeting'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM