0

我正在使用 MySQL 和 python 服务器页面来显示数据库中的数据。在数据库中,我选择了以下数据:一个列表x =[1, 61, 121, 181, 241, 301]和一个列表列表z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l']),我想将它们放在一个表格中,如下所示:

001   a b
061   c d
121   e f
181   g h
241   i j
301   k l

我是否认为我必须使用两个“for循环”来做到这一点?这是我正在使用的:

rows = cur.fetchall()
z=[]
for row in rows:
    z.append(dict[row[1]]) 
x=[]
for i in range(1, len(rows),60):
    x.append(i)
for i in range(0,len(z), 60):
    req.write("<tr><td>%s</td><td>%s</td></tr>" %(str(x[i:i+60]), str(z[i:i+60])))

这就是我输出的内容:

[1, 61, 121, 181, 241, 301]      a b
                                 c d
                                 e f
                                 g h
                                 i j
                                 k l

任何帮助将不胜感激!

4

4 回答 4

1
for index, (a, b) in zip(x, z):
    print(index, a, b)         # format as appropriate

此外,您的z列表创建可能会得到改进:

z = [dic[row[1]] for row in rows]         # calling variable dict shadows built-in

x可以创建为range(1, len(rows), 60)

于 2010-03-11T15:55:16.173 回答
1

您正在执行两次“按 60 步” x- 您正在构建x您所看到的列表,一次已按 60 步,然后获取其前 60 个项目(它没有那么多,所以你实际上得到了所有str(x[i:i+60])项目)在第二个循环中。

将第二个循环更改为,例如:

for i in range(0,len(z), 60):
    req.write("<tr><td>%s</td><td>%s</td></tr>" %(x[i//60], z[i:i+60]))

我还消除了多余的str调用,因为%s格式化已经在内部完成了。

于 2010-03-11T15:56:21.943 回答
0
#Following code will work in Python 3.x

x =[1, 61, 121, 181, 241, 301]
z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l'])

for i in zip(x, z):
    print("{0:03} {1} {2}".format(i[0], i[1][0], i[1][1]))
于 2010-03-11T16:04:22.073 回答
0
  1. 尝试使用迭代器而不是数组 + 索引。敌人示例使用xrange而不是range等。使用 2 个游标而不是缓存表中的所有内容可能是有益的(我不知道 MySQL 的功能)。

  2. 有一个zip函数需要两个可迭代的 - 比如两个数组。

示例代码:

for (xe, ze) in zip (x, z):
    req.write("<tr><td>%s</td><td>%s</td></tr>" % (xe, ' '.join(ze))
于 2010-03-11T16:04:52.690 回答