【问题标题】:Comma separating a list of dictionaries using jinja使用 jinja 分隔字典列表的逗号
【发布时间】:2014-09-29 11:40:52
【问题描述】:

我正在尝试在 python 字典数组中的项目列表之间添加逗号(使用 jinja)。

我正在做以下事情:

@{@ for row in data.results -@}@
@{{@ row.gene|join(',', attribute='gene')@}}@
@{@ endfor @}@}

然而,每个基因都属于python字典数组中的一个字典,比如

'results': [
         {'aminoacidic': u'p.Leu110Val',
          'criterium': u'1000',
          'ensembl': u'rs2301149',
          'gene': u'KCNMB1',
          'hgmd': u'CM078442',
          'nucleotidic': u'c.328C>G'},
         {'aminoacidic': None,
          'criterium': u'1000',
          'ensembl': u'rs13306673',
          'gene': u'SLC12A3',
          'hgmd': None,
          'nucleotidic': u'c.283-54T>C'},
          {'aminoacidic': None,
          'criterium': u'3000',
          'ensembl': u'rs72811418',
          'gene': u'CYBA',
          'hgmd': u'CR073543',
          'nucleotidic': u'c.*-675A>T'}
         ]

我想要以下输出:

         blabla in the gene list KCNMB1, SLC12A3, and CYBA. 

如何在 jinja 中正确添加 integer.gene 的属性,以便用逗号分隔基因?有没有什么简单的方法可以在最后一个基因前加上“and”字?

【问题讨论】:

    标签: python dictionary jinja2


    【解决方案1】:

    您可以使用loop 变量:

    {% for result in results %}
      {% if not loop.last %}{{ result.gene }}, {% else %}and {{ result.gene }}.{% endif %}
    {% endfor %}
    

    或者,将 2 个连接拼凑在一起:

    {{ (results[:results|length-1]|join(", ",attribute="gene"), (results|last).gene | join("and ") }}
    

    在这种情况下,我们获取没有最后一项的结果,并用逗号 (results[:results|length-1]|join(", ",attribute="gene")) 将其全部连接在一起,然后将其与最后一项连接。

    【讨论】:

    • 感谢清晰的解释和干净的解决方案!
    • 没问题,出于好奇,您喜欢哪种解决方案?
    • 我用的是第一个。对于可能阅读我的代码的其他人来说,这似乎更容易理解。
    猜你喜欢
    • 2021-12-29
    • 2014-08-01
    • 2013-07-03
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    相关资源
    最近更新 更多