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

时间:2013-07-17 13:35:12

标签: python csv for-loop dictionary

我有一个“asin.txt”文档:

in,Huawei1,DE
out,Huawei2,UK
out,Huawei3,none
in,Huawei4,FR
in,Huawei5,none
in,Huawei6,none
out,Huawei7,IT

我打开此文件并制作OrderedDict

from collections import OrderedDict
reader = csv.reader(open('asin.txt','r'),delimiter=',')
reader1 = csv.reader(open('asin.txt','r'),delimiter=',')
d = OrderedDict((row[0], row[1].strip()) for row in reader)
d1 = OrderedDict((row[1], row[2].strip()) for row in reader1)

然后我想创建变量(a,b,c,d),所以如果我们采用asin.txt的第一行,它应该是:a = in; b = Huawei1; c = Huawei1; d = DE。要做到这一点,我正在使用“for”循环:

from itertools import izip
for (a, b), (c, d) in izip(d.items(), d1.items()): # here
    try:
      .......

之前有效,但现在,出于某种原因,它会输出错误:

 d = OrderedDict((row[0], row[1].strip()) for row in reader)
 IndexError: list index out of range

我该如何解决?

1 个答案:

答案 0 :(得分:0)

你的文本文件中可能有一行没有至少两个由","分隔的字段。 E.g:

in,Huawei1

尝试按以下方式找到解决方案:

d = OrderedDict((row[0], row[1].strip()) for row in reader if len(row) >= 2)

l = []
for row in reader:
  if len(row) >= 2:
    l.append(row[0], row[1].strip())
d = OrderedDict(l)