indexerror:索引超出范围python错误

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

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

  1. """ This function takes in a list of emails and puts them into a sql database """
  2. # import module
  3. import sqlite3 as sql
  4. # Setup sql
  5. # create connection for sql
  6. connection = sql.connect("emailList.db")
  7. # create cursor
  8. crsr = connection.cursor()
  9. #create sql table
  10. cmd = """CREATE TABLE emails (
  11. email_handle TEXT,
  12. email_domain VARCHAR(20));"""
  13. crsr.execute(cmd)
  14. # iterate through email list
  15. index = 0
  16. for email in email_list:
  17. #split email with a delimiter of "@"
  18. email_list[index] = email.split('@')
  19. index += 1
  20. # while loop to put all data into table
  21. ct = 0
  22. index = 0
  23. while ct <= (len(email_list) - 1):
  24. for i in email_list:
  25. for j in email_list:
  26. email_address_1 = email_list[index]
  27. email_address_2 = email_list[index + 1]
  28. cmd = f"""INSERT INTO emails (email_handle, email_domain)
  29. VALUES ({email_address_1}, {email_address_2});"""
  30. crsr.execite(cmd)
  31. index += 1
  32. ct += 1
  33. # get the contents of the table
  34. crsr.execute("SELECT * FROM emails;")
  35. # store contents in a variable
  36. email_address_list = crsr.fetchall()
  37. # save changes to sql table
  38. connection.commit()
  39. # close connection
  40. connection.close()
  41. # return print statement for data
  42. 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 如果您想创建每一对可能的

  1. email_address_1 = email_list[i]
  2. email_address_2 = email_list[j]

相关问题