2013-01-03 62 views
1

我仍然试图获得蟒蛇的坑,所以忍受着我。请。我从书中使用了这些代码。该书没有正确显示代码中的空格,所以间距是我最好的猜测。此代码应该将MySQL查询的结果分解为更易读的格式。python for循环元组索引超出范围

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])部分,但是这就是它看起来像在书中,所以我不知道还有什么可以尝试的。

+0

显然'record'的长度小于'column_list'的长度。记录中有什么? – zenpoy

+1

'record'是来自上一行的循环变量。你的意思是改用'header'或'column_list'吗? –

回答

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(...))。它更习惯。

+0

+1使用zip()。还有2个字节... – hughdbrown

+0

@hughdbrown - 2个字节?我不关注... – mgilson

+0

“+1使用zip()”。长度为13个字节,并且StackOverflow不允许少于15个字符的评论。所以,我加了2个字节...... – hughdbrown

0

问题原来是白色空间,更重要的是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"