【问题标题】:Python list index out of range errorPython列表索引超出范围错误
【发布时间】:2013-12-06 09:50:58
【问题描述】:
import pandas as pd
df = pd.read_csv("email_addresses_of_ALL_purchasers.csv")
all_emails = df["Email"]
real_emails = [] 

test_domains = ['yahoo.com', 'gmail.com', 'facebook.com', 'hotmail.com']

for email in all_emails: 
    email_separated = email.split("@")
    if email_separated[1] not in test_domains:
        real_emails.append(email) 
print real_emails

我正在尝试过滤掉不同的电子邮件帐户类型。上面这段代码为什么会报错:

IndexError: 列表索引超出范围

【问题讨论】:

  • “列表索引超出范围”是一个非常不言自明的错误消息 IMO。查看导致错误的实际数据。

标签: python


【解决方案1】:

您的一封电子邮件显然不包含@。

print(email) 作为循环的第一条语句,然后您可以查看不适合的电子邮件。

【讨论】:

  • +1 最重要的是,在调试时,您应该print 变量,以便您期望在其中的内容实际上在其中。
【解决方案2】:

试试这个:

import pandas as pd
df = pd.read_csv("email_addresses_of_ALL_purchasers.csv")
all_emails = df["Email"]
real_emails = [] 

test_domains = ['yahoo.com', 'gmail.com', 'facebook.com', 'hotmail.com']

for email in all_emails: 
    email_separated = email.split("@")
    try:
        if email_separated[1] not in test_domains:
            real_emails.append(email)
    except IndexError:
        print('Mail {} does not contain a @ sign'.format(email))
print real_emails

【讨论】:

  • 我们也可以直接使用pandasprint all_emails[~all_emails.str.contains("@")]
【解决方案3】:

在此处使用partition 更加健壮。如果 @ 丢失 - domain 将只是空字符串

for email in all_emails: 
    name, delim, domain = email.partition("@")
    if domain and domain not in test_domains:

维基百科也有一个list of unusual but valid email address examples,可能会让你大吃一惊

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 2016-01-06
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多