按python中的特定电子表格列分组

时间:2018-07-18 16:18:29

标签: python flask

如果我有一张这样的桌子,

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一样多,这就是为什么我要按NAMECHECK_TYPE进行分组的原因我在相应的按钮下分别只有4个按钮和10个测试。

1 个答案:

答案 0 :(得分:0)

为简化问题,您有一个字典列表,并且希望唯一的字典创建按钮。我认为您的数据已经为NAME订购了。

您的标记确实不是数据处理的地方。您可以使用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 %}