如果我有一张这样的桌子,
TEST_ID COUNT NAME CHECK_TYPE ITEMS
1 1 firstName First Name This is the first test
2 2 secondName Second Name This is the second test
2 3 secondName Second Name Tis is the third test
2 4 secondName Second Name This is the fourth test
3 5 thirdName Third Name This is the fifth test
3 6 thirdName Third Name This is the sixth test
4 7 fourthName Fourth Name This is the seventh test
4 8 fourthName Fourth Name This is the eighth test
4 9 fourthName Fourth Name This is the ninth test
4 10 fourthName Fourth Name This is the tenth test
如何对其进行分组,以使我的CHECK_TYPE
值只显示一次?
我的数据读取函数定义为:
def read_excel_data(flin='data_in.xlsx'):
book = xlrd.open_workbook(flin)
sheet = book.sheet_by_index(0)
header = []
records = []
for row in sheet.get_rows():
if len(header) == 0:
header.extend([x.value for x in row])
else:
dict_row = {x:y.value for x,y in zip(header,row)}
records.append(dict_row)
return records
我的路线被定义为,
@app.route('/show_data', methods=['GET', 'POST'])
def show_data():
excel_data = read_excel_data()
return render_template('template.html', data = excel_data)
在我的HTML中,我将其设置为,
{%for alias in data%}
<button name='{{alias.NAME}}' type='button' class='drop'>{{alias.CHECK_TYPE}}</button>
<div class='panel'>
{%for _item in data
if _item.NAME == alias.NAME %}
<div>
<br>
<span name='item{{_item.COUNT}}'>{{_item.ITEMS}}</span>
<select name='op{{_item.COUNT}}' class='menu' style='float:right'>
<option value=''>--Select one--</option>
<option value='Yes'>Yes</option>
<option value='No'>No</option>
<option value='NA'>N/A</option>
</select>
</div>
<br>
<hr>
{%endfor%}
</div>
{%endfor%}
</div>
现在的问题是,它创建的button
标签和ITEMS
一样多,这就是为什么我想按NAME
或CHECK_TYPE
分组,所以我只有4个按钮和10个测试分别在它们相应的按钮下。
发布于 2018-07-19 08:56:27
简化这个问题,你有一个字典列表,你想让唯一的字典来创建按钮。我假设你的数据已经按名字排序了。
您的标记确实不是用于数据处理的地方。您可以使用OrderedDict来收集唯一的NAME和CHECK_TYPE对。
from collections import OrderedDict
...
def show_data():
excel_data = read_excel_data()
groups = list(OrderedDict((x['NAME'], x['CHECK_TYPE']) for x in data).items())
return render_template('template.html', data = excel_data, groups=groups)
现在在您的模板中
{%for alias_name, alias_check_type in groups%}
<button name='{{alias_name}}' type='button' class='drop'>{{alias_check_type}}</button>
...
if _item.NAME == alias_name %}
https://stackoverflow.com/questions/51406743
复制相似问题