错误列表索引必须是整数,只要我不使用输入来获取参数,它就可以工作

2024-09-26 22:07:21 发布

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

我试过:

def funct(arg, list):
 Diferent_list=[]

 for i in arg:
     Diferent_list=Diferent_list+([list[1:][i][0:6]])

为什么这样做

funct((1,2,3),list)

但如果我说:

arg= input((1,2,3))
funct(arg,list)

(inside input()我将我所输入的内容用于测试提示符

它给

TypeError: list indices must be integers or slices, not str

这就是为什么我需要它是(1,2,3)或任何“元组”

a = ['+'.join(s for s, _, _, _, _,_ in list), sum(x + y + z + c+v for _, x, y, z, c,v in distritos)
you can ignore that part
#, sum(q+w+e+r+t+y+u+i+o+p+a+s+d+f+g+h+j+k+l+ç for q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,ç in anotherlist)]

Tags: in内容forinputdefarglistsum
2条回答

正如markmeyer的注释所指出的,input()在python3.x中总是返回一个str。因此,将您的代码修改为以下内容以获得整数:

arg = int(arg)

但是请注意,如果他们键入的不是数字的内容,则此操作可能会失败,因此如果您希望更健壮一点,则应该在try:块中执行转换,并查找表示转换不起作用的ValueError异常。最后,你可以把它包装成一个while循环,让他们继续尝试,直到最后输入一个实际的数字(while循环可能对您的应用程序来说过于致命,在这种情况下,只需打印一条错误消息,并在出现异常时执行sys.exit() )你知道吗

import sys

while True:
    arg= input('(1,2,3, or q to quit) ')
    if arg == 'q':        # users just wants out, so sys.exit()
        sys.exit(0)
    try:
         arg = int(arg)
    except ValueError:    # int(arg) failed to convert
         print("bad number please try again")
    else:
         break            # NO exception occurred so number is good
                          # so break out of loop and move on 
eval() is the awnser

例如eval(input(“Put list you want to group here(It needs in the form[a,b,c])))

相关问题 更多 >

    热门问题