如何将列表转化为模板化的类对象

2024-03-29 06:35:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将列表列表转换为一个类,以便为每个对象(如foo.bar.spam)调用该类?你知道吗

列表列表:

information =[['BlueLake1','MO','North','98812'], ['BlueLake2','TX','West','65343'], ['BlueLake3','NY','sales','87645'],['RedLake1','NY','sales','58923'],['RedLake2','NY','sales','12644'],['RedLake3','KY','sales','32642']]

这将是使用Flask中的jinja2模板为一个非常大的html表创建变量。你知道吗

我希望能够做到这样:

{% for x in information %}
    <tr>
        <td>{{x.name}}</td>
        <td>Via: {{x.location}} | Loop: {{x.region}}</td>
        <td>{{x.idcode}}</td>
    </tr>
{% endfor %}

有其他的用途,然后只有这一个模板与此信息,因此我希望它是一个可调用类在其他地方使用。你知道吗


Tags: 对象模板列表informationfoobarspamtr
2条回答

使用^{}

>>> from collections import namedtuple
>>> Info = namedtuple('Info', ['name', 'location', 'region', 'idcode'])
>>>
>>> information =[
...     ['BlueLake1','MO','North','98812'],
...     ['BlueLake2','TX','West','65343'],
...     ['BlueLake3','NY','sales','87645'],
...     ['RedLake1','NY','sales','58923'],
...     ['RedLake2','NY','sales','12644'],
...     ['RedLake3','KY','sales','32642']
... ]
>>> [Info(*x) for x in information]
[Info(name='BlueLake1', location='MO', region='North', idcode='98812'),
 Info(name='BlueLake2', location='TX', region='West', idcode='65343'),
 Info(name='BlueLake3', location='NY', region='sales', idcode='87645'),
 Info(name='RedLake1', location='NY', region='sales', idcode='58923'),
 Info(name='RedLake2', location='NY', region='sales', idcode='12644'),
 Info(name='RedLake3', location='KY', region='sales', idcode='32642')]

可能最常见的方法是把每一条记录都放入一个dict中

info = []
for r in information:
    record = dict(name=r[0], location=r[1], region=r[2], idcode=r[3])
    info.append(record)

然后,Jinja2允许您使用x.name等访问属性,就像您在示例中所做的那样。你知道吗

{% for x in info %}
    <tr>
        <td>{{x.name}}</td>
        <td>Via: {{x.location}} | Loop: {{x.region}}</td>
        <td>{{x.idcode}}</td>
     </tr>
{% endfor %}

注意,这种索引到数据(x.name)的方法是一种特定于jinja2的快捷方式(尽管它是从django模板偷来的,而django模板可能是从其他地方偷来的)。你知道吗

在python本身中,您必须:

for x in info:
    print(x['name'])
    # x.name will throw an error since name isn't an 'attribute' within x
    # x['name'] works because 'name' is a 'key' that we added to the dict

相关问题 更多 >