JSON结合python循环只打印整数

时间:2016-10-19 14:10:17

标签: python loops count increment

我正在尝试基于之前提供的变量循环遍历json列表中的整数。这是我的JSON列表:

    tracks =[
   {
      'album_name':'Nevermind',
      1:'Smells like teen spirit',
      2:'In Bloom',
      3:'Come as you are',
      4:'Breed',
      5:'Lithium',
      6:'Polly',
      7:'Territorial Pissings',
      8:'Drain You',
      9:'Lounge act',
      10:'Stay away',
      11:'On a plain',
      12:'Something in the way'
   },
   {
      'album_name':'Relapse',
      1:'Hello',
      2':'3AM',

   },

]

这是我的html循环:

<div class="single_album">
    <h2>Track list</h2>
    {% for tracks in tracks if tracks.album_name == album_name %}
        <ol>
            <li>{{ tracks[x] }}</li>
        </ol>
    {% endfor %}
</div>

如果我把1代替'x'就行了,因为它打印了第一个记录,即“1:'闻起来像青少年精神'”但是我不知道如何制作一个循环,其中x将增加每次循环,因为我不确定它是否应该放在python或html文件中。

1 个答案:

答案 0 :(得分:0)

In [15]: from django.template import Template,Context    
In [16]: tracks =[
        ...:    {
        ...:       'album_name':'Nevermind',
        ...:       1:'Smells like teen spirit',
        ...:       2:'In Bloom',
        ...:       3:'Come as you are',
        ...:       4:'Breed',
        ...:       5:'Lithium',
        ...:       6:'Polly',
        ...:       7:'Territorial Pissings',
        ...:       8:'Drain You',
        ...:       9:'Lounge act',
        ...:       10:'Stay away',
        ...:       11:'On a plain',
        ...:       12:'Something in the way'
        ...:    },
        ...:    {
        ...:       'album_name':'Relapse',
        ...:       1:'Hello',
        ...:       2:'3AM',
        ...:
        ...:    },
        ...:
        ...: ]

    In [17]: t = Template("""<div class="single_album"> <h2>Track list</h2> {% for track in tracks %} {%if track.album_name == album_name %}<ol> {% for key, value in track
        ...: .items %} {%if key != 'album_name' %}<li>{{value}}</li>{%endif%} {% endfor%} </ol>{%endif%} {% endfor %} </div>""")

    In [18]: c = Context({"tracks": tracks,'album_name':'Nevermind'})

    In [19]: t.render(c)
    Out[19]: u'<div class="single_album"> <h2>Track list</h2>  <ol>  <li>Smells like teen spirit</li>  <li>In Bloom</li>  <li>Come as you are</li>  <li>Breed</li>  <li>Lithium</li>  <li>Polly</li>  <li>Territorial Pissings</li>  <li>Drain You</li>  <li>Lounge act</li>  <li>Stay away</li>  <li>On a plain</li>  <li>Something in the way</li>    </ol>    </div>'

    In [20]: