【问题标题】:Python 3.3 IndexError doesn't make sensePython 3.3 IndexError 没有意义
【发布时间】:2014-06-20 19:17:18
【问题描述】:

我在py3.3中有一个多维数组,看起来像

[ # big container

  [ # month container

    ['date string', 'temp'],['date string', 'temp'] #dates in month

  ], #close month container

  [ # next month container

    ['date string', 'temp'], ['date string', 'temp']

  ]

]

这是我的代码:

dailyDict = []
dailyRow = []
compareStation = 'myfile.csv'
with open(compareStation, newline='\n') as csvfile:
            station = csv.reader(csvfile, delimiter=',', quotechar='|')
            for row in station:
                if 1stDayOfMonthCondition:
                    dailyDict.append(dailyRow)
                    dailyRow = []
                    dailyRow.append(row)
                else:
                    dailyRow.append(row)

for month in dailyDict:
        print(month[1])

这给了我一个 IndexError,列表索引超出范围。 但是,当我运行 print(month) 时,我每个月都会打印出来就好了。

当我将打印的月份设置为变量时,例如 x,在 shell 中,我可以 print(x[1]) 就好了。但是print(month[1]) 仍然失败。很困惑。

谢谢。

【问题讨论】:

  • 打印month有什么好处?
  • dailyDict = []!这就是为什么你不应该在变量名中写对象的类型。

标签: python arrays list multidimensional-array


【解决方案1】:

索引列表从 0 而不是 1 开始,所以你应该尝试print(month[0])看看你是否得到任何东西

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    相关资源
    最近更新 更多