【问题标题】:python for loop tuple index out of rangepython for循环元组索引超出范围
【发布时间】:2013-01-07 11:57:16
【问题描述】:

我仍在尝试掌握 python 的窍门,所以请耐心等待。请。我有这段代码,我正在使用一本书。这本书没有正确显示代码中的空白,所以间距是我最好的猜测。此代码应该将 MySQL 查询的结果分解为更易读的格式。

if form is True:
columns_query = """DESCRIBE %s""" % (table)
print columns_query
columns_command = cursor.execute(columns_query)
headers = cursor.fetchall()
column_list = []
for record in headers:
    column_list.append(record[0])
output=""
for record in results:
    output = output + "===================================\n\n"
for field_no in xrange(0, len(column_list)):
    output = output + column_list[field_no] + ": " + str(record[field_no]) + "\n"
output = output + "\n"

当我尝试运行它时,我得到以下信息:

Traceback (most recent call last):
  File "odata_search.py", line 46, in <module>
    output = output + column_list[field_no] + ": " + str(record[field_no]) + "\n"
IndexError: tuple index out of range

它与代码的str(record[field_no]) 部分有关,但这是书中的样子,所以我不确定还有什么可以尝试的。

【问题讨论】:

  • 显然record 的长度小于column_list 的长度。 record 中有什么内容?
  • record 是上一行的循环变量。您的意思是改用headerscolumn_list 吗?

标签: python


【解决方案1】:

显然len(record) != len(column_list)。 (具体来说,column_list record)。您是否有理由认为它们的长度相同?

一个“修复”是这样的:

for col,rec in zip(column_list,record):
    output += col + ": " + str(rec) + "\n"

代替:

for field_no in xrange(0, len(column_list)):
    output = output + column_list[field_no] + ": " + str(record[field_no]) + "\n"

这将截断column_listrecord 中较短的输出。

无论如何,我都建议使用zip 而不是range(0,len(...))。它更加地道。

【讨论】:

  • “+1 使用 zip()。”长度为 13 个字节,并且 StackOverflow 不允许少于 15 个字符的 cmets。所以,我加了 2 个字节...
  • @hughdbrown -- 哦,我以为你在评论答案。我现在和你一起跟踪:)。我想我会直接把 . 变成一个省略号,然后收工,但这样我就有点笑了。
  • 好吧,然后检查一下类似的娱乐:stackoverflow.com/questions/3753364/…
【解决方案2】:

问题出在空白处,更重要的是 MySQL 查询本身。我拉的是一个列中的行列表,而不是拉一行的所有列,这是编写循环连接的内容。我将在错误查询的结果中返回的记录数不等于包含所有列的列表中的结果数。该代码还打算成为循环中的循环,因此我在顶部的间距是错误的。它应该如下所示。我在它之前添加了几行来显示我必须修改的查询:

旧语句循环如下:

statement = """select %s from %s where %s like '%s' limit 10""" % (column, table, column, term)

应该是这样的:

statement = """select * from %s where %s like '%s' limit 10""" % (table, column, term)

command = cursor.execute(statement)
results = cursor.fetchall()

column_list = []
for record in results:
    column_list.append(record[0])

循环内循环:

if form is True:
columns_query = """DESCRIBE %s""" % (table)
columns_command = cursor.execute(columns_query)
headers = cursor.fetchall()
column_list = []
for record in headers:
    column_list.append(record[0])
output=""
for record in results:
    output = output + "===================================\n\n"
    for field_no in xrange(0, len(column_list)):
        output = output + column_list[field_no] + ": " + str(record[field_no]) + "\n"
    output = output + "\n"

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    相关资源
    最近更新 更多