开发者

Python ~ accessing tuple members in template class

I am new to Python - be forewarned!

I have a template class that takes a list as an argument and applies the members of the list to the template. Here's the first class:

class ListTemplate:

    def __init__(self, input_list=[]):
        self.input_list = input_list

    def __str__(self):
        return "\n".join([self._template % x for x in self.input_list])

Here's the template code/class:

class HTML_Template(ListTemplate):

    _template = """ 
      <li>
        <table width="100%%" border="0">
          <tr>开发者_JS百科
            <td>Title: %(title)s</td>
            <td>Link: %(isbn)s</td>
          </tr>
          <tr>
            <td>Author: %(author)s</td>
            <td>Date: %(pub_date)s</td>
          </tr>
          <tr>
            <td>Summary: %(isbn)s</td>
            <td>Description: %(descr)s</td>
          </tr>
        </table>
        <hr>
      </li>"""

Here's the problem:

I'm pulling data from a sqlite database using fetchall, which return a list of tuples. I can pass this list of tuples to this method fine by changing the template to %s instead of %(isbn) ...etc., however, I need to access the isbn member multiple times in the template. To do this now, I load the tuples in to dictionaries and push them into another list ...then pass the list of dictionaries. This strikes me as inefficient. My question is: how would you rewrite this so that the original list of tuples could be passed to the template (thus, saving a step ), while still allowing access to the individual members by ie., item[0] or similar?

Thanks ~

Bubnoff


If you use the new string formatting, it may be possible to operate solely on indices...

But that will be horrible to decipher, even with the database scheme at hand. The list-of-dict approach sounds much saner, and unless you operate a really frequently-visited service, the performance impact won't be too bad (this depends on the size of the data set - but you don't get 3k 7-tuples at once, do you?). Dictionaries are rather efficient in Python. Caching could also help performance-wise.


If you are using Python 2.6 or newer, you can use the format method of strings instead of the % operator. This allows you to specify the index of the given arguments:

>>> template = 'First value: {0}, Second value: {1}, First again: {0}'
>>> values = (123, 456)
>>> template.format(*values)
'First value: 123, Second value: 456, First again: 123'
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜