【发布时间】:2014-10-06 23:41:24
【问题描述】:
我是 python 新手,正在使用python-weather-api。我正在尝试将这个 JSON 结构转换为 list(这是我在 Java 中知道的名称,如果不是,抱歉)。
'forecasts': [ { 'code': u'34',
'date': u'27 Mar 2013',
'day': u'Wed',
'high': u'9',
'low': u'2',
'text': u'Mostly Sunny'},
{ 'code': u'28',
'date': u'28 Mar 2013',
'day': u'Thu',
'high': u'10',
'low': u'2',
'text': u'Mostly Cloudy'},
{ 'code': u'30',
'date': u'29 Mar 2013',
'day': u'Fri',
'high': u'11',
'low': u'3',
'text': u'Partly Cloudy'},
{ 'code': u'30',
'date': u'30 Mar 2013',
'day': u'Sat',
'high': u'11',
'low': u'3',
'text': u'Partly Cloudy'},
{ 'code': u'28',
'date': u'31 Mar 2013',
'day': u'Sun',
'high': u'10',
'low': u'7',
'text': u'Mostly Cloudy'}],
例如,要访问第一个值,我正在这样做:
forecast = {
'day_0': yahoo_result['forecasts'][0]['day'],
}
这就是我现在正在做的事情:
views.py
forecast = {
'day_0': yahoo_result['forecasts'][0]['day'],
'text_0': yahoo_result['forecasts'][0]['text'],
'high_0': yahoo_result['forecasts'][0]['high'],
'low_0': yahoo_result['forecasts'][0]['low'],
'day_1': yahoo_result['forecasts'][1]['day'],
'text_1': yahoo_result['forecasts'][1]['text'],
'high_1': yahoo_result['forecasts'][1]['high'],
'low_1': yahoo_result['forecasts'][1]['low'],
'day_2': yahoo_result['forecasts'][2]['day'],
'text_2': yahoo_result['forecasts'][2]['text'],
'high_2': yahoo_result['forecasts'][2]['high'],
'low_2': yahoo_result['forecasts'][2]['low'],
'day_3': yahoo_result['forecasts'][3]['day'],
'text_3': yahoo_result['forecasts'][3]['text'],
'high_3': yahoo_result['forecasts'][3]['high'],
'low_3': yahoo_result['forecasts'][3]['low'],
'day_4': yahoo_result['forecasts'][4]['day'],
'text_4': yahoo_result['forecasts'][4]['text'],
'high_4': yahoo_result['forecasts'][4]['high'],
'low_4': yahoo_result['forecasts'][4]['low'],
}
return render(request, 'index.html', {'weather':weather, 'forecast': forecast})
并在 HTML 中显示结果:
<div class="col-md-9">
<ul>
<li> <!-- start the loop right here -->
<h2>{{ forecast.day_0 }}</h2>
<i class=" ico-cloudy text-primary"></i>
<div class="statistics"> low {{ forecast.low_0 }}</div>
<div class="statistics"> high {{ forecast.high_0 }}</div>
</li>
<li>
<h2>{{ forecast.day_1 }}</h2>
<i class=" ico-cloudy text-primary"></i>
<div class="statistics"> low {{ forecast.low_1 }}</div>
<div class="statistics"> high {{ forecast.high_1 }}</div>
</li>
<li>
<h2>{{ forecast.day_2 }}</h2>
<i class=" ico-cloudy text-primary"></i>
<div class="statistics"> low {{ forecast.low_2 }}</div>
<div class="statistics"> high {{ forecast.high_2 }}</div>
</li>
<li>
<h2>{{ forecast.day_3 }}</h2>
<i class=" ico-cloudy text-primary"></i>
<div class="statistics"> low {{ forecast.low_3 }}</div>
<div class="statistics"> high {{ forecast.high_3 }}</div>
</li>
<li>
<h2>{{ forecast.day_4 }}</h2>
<i class=" ico-cloudy text-primary"></i>
<div class="statistics"> low {{ forecast.low_4 }}</div>
<div class="statistics"> high {{ forecast.high_4 }}</div>
</li>
</ul>
</div>
但是我想把整个结构放在一个列表中以便能够在 HTML 文件中循环之后,我该怎么做呢?
【问题讨论】:
标签: python django loops python-2.7 django-views