我的代码:
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
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)
我收到了IndexError:
文件“ c:/ Users / USER / Desktop /电子邮件grabber.py”,第82行,在 email_address_grab([“ testemail123@gmail.com”])
文件“ c:/Users/USER/Desktop/emailgraber.py”,第57行,在email_address_grab中 email_address_2 = email_list [索引+ 1]
IndexError:列表索引超出范围
我该如何解决?
答案 0 :(得分:0)
您有2个循环在email_list上进行迭代。但是,您仅在代码中使用变量index
,并且每次都将其递增。
因此,假设您的列表中有10封电子邮件。您的双循环将使您的代码执行100次,并且index
的值将继续增长。在执行了11次循环之后,您将尝试获取email_list
的第11个值,这会产生错误,因为列表中只有10个值。
如果您想创建每对变量,您可能想要使用i, j
这样的变量
email_address_1 = email_list[i]
email_address_2 = email_list[j]