indexerror:索引超出范围python错误

2wnc66cl  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(403)

我的代码:
定义电子邮件地址(电子邮件列表):

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

index = 0
for email in email_list:
    #split email with a delimiter of "@"
    email_list[index] = email.split('@')
    index += 1

# while loop to put all data into table

ct = 0
index = 0
while ct <= (len(email_list) - 1):
    for i in email_list:
        for j in email_list:
            email_address_1 = email_list[index]
            email_address_2 = email_list[index + 1]
            cmd = f"""INSERT INTO emails (email_handle, email_domain)
            VALUES ({email_address_1}, {email_address_2});"""
            crsr.execite(cmd)
            index += 1
    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)

我得到一个索引器:
文件“c:/users/user/desktop/email grabber.py”,第82行,在email\u address\u grab([”testemail123@gmail.com"])
文件“c:/users/user/desktop/email grabber.py”,第57行,在email\u address\u grab email\u address\u 2=email\u list[index+1]
索引器错误:列表索引超出范围
我怎样才能解决这个问题?

8cdiaqws

8cdiaqws1#

你有两个循环在电子邮件列表上循环。但是,您只使用您的变量 index 在你的代码中,你每次都增加它。
假设你的名单上有10封邮件。双循环将使代码执行100次 index 将继续增长。在循环执行11次之后,您将尝试获取循环的第11个值 email_list 这将产生错误,因为列表中只有10个值。
你可能想做的是使用你的 i, j 如果您想创建每一对可能的

email_address_1 = email_list[i]
email_address_2 = email_list[j]

相关问题