【问题标题】:For-in-loop Multidimensional list IndexErrorFor-in-loop 多维列表 IndexError
【发布时间】:2020-11-17 08:24:50
【问题描述】:

我得到了一个列表IndexError: list index out of range。以下是我的代码

def email_address_grab(email_list):
    """ This function takes in a list of emails and puts them into a sql database""" 
    
    # import module
    import sqlite3 as sql

    # Setup sql
    # create connection for sql
    connection = sql.connect("emailList.db")

    # create cursor
    crsr = connection.cursor()

    # create sql table
    cmd = """CREATE TABLE emails (
    email_handle TEXT,
    email_domain VARCHAR(20));"""
    crsr.execute(cmd)


    # iterate through email list
    for index, email in enumerate(email_list):
        #split email with a delimiter of "@"
        email_list[index] = email.split('@')

    # while loop to put all data into table
    ct = 1
    index = 0
    while ct <= len(email_list):
        for i in email_list:
            for j in i:
                email_address_1 = email_list[index][index]
                email_address_2 = email_list[index][index + 1]
                cmd = f"""INSERT INTO emails (email_handle, email_domain) VALUES ("{email_address_1}", "{email_address_2}");"""
                crsr.execute(cmd)
                index += 1
                #print(cmd)
        ct += 1


    # get the contents of the table
    crsr.execute("SELECT * FROM emails;")
    
    # store contents in a variable
    email_address_list = crsr.fetchall()

    # save changes to sql table
    connection.commit()

    # close connection
    connection.close()

    # return print statement for data
    # return print(email_address_list)

错误:

Traceback (most recent call last):

  File "c:/Users/USER/Desktop/email grabber.py", line 78, in <module>
    email_address_grab(["test@gmail.com", "test2@gmail.com"])
  File "c:/Users/USER/Desktop/email grabber.py", line 53, in email_address_grab
    email_address_2 = email_list[index][index + 1]

IndexError: list index out of range

【问题讨论】:

  • 尝试删除此比较while ct &lt;= len(email_list): 中的= 符号,您可能希望将ct 初始化为0
  • index指向列表的最后一个元素时,index + 1在列表之外。

标签: python sqlite for-loop while-loop index-error


【解决方案1】:

你不应该在第二个下标中使用index

                email_address_1 = email_list[index][index]
                email_address_2 = email_list[index][index + 1]

email_list[index] 的每个元素只有两个元素,句柄和域。使用主列表中的索引作为嵌套列表的索引是没有意义的。

你想要的是:

email_address_1, email_address_2 = email_list[index]

其实整个循环是不必要的。将executemany() 与占位符一起使用,它会自动循环遍历列表。

cmd = "INSERT INTO emails (email_handle, email_domain) VALUES (?, ?);"
crsr.executemany(cmd, email_list)

【讨论】:

  • 使用 executemultiple 得到一个 AttributeError。它没有工作
  • 现在出现操作错误:sqlite3.OperationalError: near "%": syntax error
  • 我假设您使用的是 mysql,它使用 %s 作为占位符。 sqlite 使用?
  • 我没注意到import sqlite3
猜你喜欢
  • 1970-01-01
  • 2019-06-01
  • 2015-02-12
  • 2016-07-28
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
相关资源
最近更新 更多