简体   繁体   English

Python列表:IndexError:列表索引超出范围

[英]Python List: IndexError: list index out of range

When I try to print splited_data[1] I'm getting error message IndexError: list index out of range , On the other hand splited_data[0] is working fine. 当我尝试打印splited_data[1] ,出现错误消息IndexError: list index out of range ,另一方面, splited_data[0]正常工作。 I want to insert data into MySQL. 我想将数据插入MySQL。 splited_data[0] are my MySQL columns and splited_data[1] is mysql column values. splited_data[0]是我的MySQL列, splited_data[1]是mysql列值。 I want if splited_data[1] is empty then insert empty string in mysql. 我想如果splited_data[1]为空,然后在mysql中插入空字符串。 But I'm getting IndexError: list index out of range . 但是我得到IndexError: list index out of range How to avoid this error? 如何避免这个错误? Please help me. 请帮我。 thank you 谢谢

Here is my code. 这是我的代码。 Which is working fine. 哪个工作正常。 I'm only get this error message when splited_data[1] is empty. splited_data[1]为空时,我只会收到此错误消息。

    def clean(data):
        data = data.replace('[[','')
        data = data.replace(']]','')
        data = data.replace(']','')
        data = data.replace('[','')
        data = data.replace('|','')
        data = data.replace("''",'')
        data = data.replace("<br/>",',')
        return data


for t in xml.findall('//{http://www.mediawiki.org/xml/export-0.5/}text'):
    m = re.search(r'(?ms).*?{{(Infobox film.*?)}}', t.text)
    if m:
        k =  m.group(1)
        k.encode('utf-8')
        clean_data = clean(k) #Clean function is used to replace garbase data from text
        filter_data = clean_data.splitlines(True) # splited data with lines
        filter_data.pop(0)
        for index,item in enumerate(filter_data):
                splited_data = item.split(' = ',1)
                print splited_data[0],splited_data[1]

# splited_data[0] used as mysql column 
# splited_data[1] used as mysql values

here is Splited_data data 这是Splited_data数据

[u' music         ', u'Jatin Sharma\n']
[u' cinematography', u'\n']
[u' released      ', u'Film datedf=y201124']
split_data = item.partition('=')
# If there was an '=', then it is now in split_data[1],
# and the pieces you want are split_data[0] and split_data[2].
# Otherwise, split_data[0] is the whole string, and
# split_data[1] and split_data[2] are empty strings ('').

尝试删除等号两边的空格,如下所示:

splited_data = item.split('=',1)

A list is contiguous. list是连续的。 So you need to make sure it's length is greater than your index before you try to access it. 因此,在尝试访问它之前,需要确保它的长度大于索引的长度。

'' if len(splited_data) < 2 else splited_data[1]

You could also check before you split: 您还可以在拆分之前进行检查:

if '=' in item:
    col, val=item.split('=',1)
else:
    col, val=item, ''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM