列表索引超出范围? [英] List index out of range?

查看:40
本文介绍了列表索引超出范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def print_db():con = lite.connect('master.db')打印('输入名字:')名字 = 输入('> ')与骗局:cur = con.cursor()数据 = cur.fetchone()cur.execute("SELECT * FROM Contacts WHERE First = (?);", (firstname,))list_title = ['名字'、'姓氏'、'电话'、'电子邮件']k = 0因为我在cur:打印(\n")对于 i 中的 j:打印 (list_title[k],)打印 (j)如果 k<5:k+=1其他:k = 0打印(数据)打印('输入1返回主菜单')userinput = input('>')如果用户输入==1":主要()其他:主要()

<块引用>

回溯列表索引在打印时超出范围 (list_title)[k],)

好的更新,所以你可以看到整个功能.

解决方案

k <5 仍然为真,直到 k 达到 5,这意味着 k 的最大数量为 4.请记住,列表索引从 0 开始计数,因此 k 的最高索引是 3.

所以,当你尝试获取list_title[4]时,你会得到一个IndexError.

你必须改变 k <5k <4.

for j in i:打印 (j)如果 k<4:print (list_title[k],) #移动到这里的条件k+=1其他:k = 0

这样,当k的值为4时,k会被重置为0,并且错误永远不会发生.

希望这会有所帮助!

def print_db():
    con = lite.connect('master.db')
    print ('Enter a first name:')
    firstname = input('> ')
    with con:
        cur = con.cursor()
        data = cur.fetchone()
        cur.execute("SELECT * FROM Contacts WHERE First = (?);", (firstname,))
        list_title = ['First Name', 'Last Name', 'Phone', 'Email']
        k = 0
        for i in cur:
            print ("\n")
            for j in i:
                print (list_title[k],)
                print (j)
                if k < 5: k+=1
                else:
                    k = 0

    print (data)
    print ('Enter 1 to return to main menu')
    userinput = input('> ')
    if userinput == "1":
        main()
    else:
        main()

traceback list index out of range at print (list_title)[k],)

Ok updated so you can see the whole function.

解决方案

k < 5 will still be true until k reaches 5, which means the maximum number of k is 4. Remember, list indices start counting from 0, so the highest index for k is 3.

So, when you try to getlist_title[4], you'll get an IndexError.

You'll have to change k < 5 to k < 4.

for j in i:
            print (j)
            if k < 4: 
                print (list_title[k],) #Move it to the condition here
                k+=1
            else:
                k = 0

This way, when the value of k is 4, k will be reset to 0, and the error will never happen.

Hope this helps!

这篇关于列表索引超出范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆