Python 使用jinja分隔词典列表的逗号

Python 使用jinja分隔词典列表的逗号,python,dictionary,jinja2,Python,Dictionary,Jinja2,我试图在python中字典数组中的项目列表之间添加一个逗号(使用jinja) 我正在做以下工作: @{@ for row in data.results -@}@ @{{@ row.gene|join(',', attribute='gene')@}}@ @{@ endfor @}@} 然而,每个基因都属于python中一系列字典中的一个字典,例如 'results': [ {'aminoacidic': u'p.Leu110Val', 'criteriu

我试图在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”字放在最后一个基因之前?

您可以使用以下变量:

{% for result in results %}
  {% if not loop.last %}{{ result.gene }}, {% else %}and {{ result.gene }}.{% endif %}
{% endfor %}
或者,将两个连接拼接在一起:

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

在本例中,我们获取不包含最后一项的结果,并使用逗号(
results[:results | length-1]| join(“,”,attribute=“gene”)
)将其与最后一项连接起来。

感谢您的清晰解释和干净的解决方案!没问题,出于好奇,你更喜欢哪种解决方案?我用了第一种。对于可能阅读我的代码的其他人来说,这似乎更容易理解。