开发者

Python server pages, tables and lists

开发者 https://www.devze.com 2022-12-22 11:05 出处:网络
I am using MySQL and python server pages to show the data in a database. In the db I have selected this data: a list x =[1, 61, 121, 181, 241, 301] and a list of lists z = ([\'a\',\'b\'],[\'c\',\'d\']

I am using MySQL and python server pages to show the data in a database. In the db I have selected this data: a list x =[1, 61, 121, 181, 241, 301] and a list of lists z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l']) and I would like to put these in a table to look like:

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

Am I right in thinking that I would have to use two 'for loops' to do this? Here is what I am using:

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])))

And this is what I'm outputting:

[1, 61, 121, 181, 241, 301]      a b
                                 c d
                                 e f
                                 g h
                                 开发者_如何学Goi j
                                 k l

Any help would be massively appreciated!


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

Also, your creation of z list might be improved upon:

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

x can either be created as range(1, len(rows), 60)


You're doing the "step by 60" twice on x -- you're building x to have exactly the list you see, already stepped by 60 at a time, and then getting its first 60 items (it doesn't have that many, so you're getting all items in fact) with the str(x[i:i+60]) in the second loop.

Change the second loop to, e.g.:

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]))

I've also eliminated the redundant str calls since the %s formatting already does that internally.


#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]))


  1. Try to use iterators instead of arrays + indekses. Foe example use xrange instead of range etc. It might be beneficial (I don't know MySQL capabilities) to use 2 cursors instead of caching everything in table.

  2. There is zip function which takes two iteratable - like two arrays.

Example code:

for (xe, ze) in zip (x, z):
    req.write("<tr><td>%s</td><td>%s</td></tr>" % (xe, ' '.join(ze))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号