如何将列表的列表转换为可以为每个对象调用的类,如 foo.bar.spam
?
列表列表:
信息=[['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 %}
除了这个包含此信息的模板之外,还有其他用途,因此我希望它成为一个可调用类以在其他地方使用。
最佳答案
>>> 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')]
关于python - 如何将列表转换为 Flask 模板的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26310713/