You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django开发需求:实现题目按难度等级升序展示(易到难)

按难度分类并升序展示题目

1. 数据库查询排序

直接在SQL查询中通过自定义规则按难度升序(easy → medium → hard)返回数据,避免后续额外排序:

SELECT * FROM questions
ORDER BY 
    CASE difficulty
        WHEN 'easy' THEN 1
        WHEN 'medium' THEN 2
        WHEN 'hard' THEN 3
        ELSE 4  # 处理未知难度的题目,放在最后
    END ASC;

2. 业务层分组处理

如果需要将不同难度的题目归类展示,可在查询后通过代码分组。以下是Python示例:

# 模拟从数据库获取的题目数据
questions = [
    {"id": 1, "title": "数组求和", "difficulty": "medium"},
    {"id": 2, "title": "两数之和", "difficulty": "easy"},
    {"id": 3, "title": "动态规划背包问题", "difficulty": "hard"},
    {"id": 4, "title": "字符串反转", "difficulty": "easy"}
]

# 预定义难度升序列表,确保顺序正确
sorted_levels = ['easy', 'medium', 'hard']
# 初始化分类容器
categorized = {level: [] for level in sorted_levels}

# 遍历题目填充分类
for q in questions:
    level = q['difficulty']
    if level in categorized:
        categorized[level].append(q)

# 按升序输出分类结果
for level in sorted_levels:
    print(f"\n=== {level.upper()} 题目 ===")
    for idx, q in enumerate(categorized[level], 1):
        print(f"{idx}. {q['title']}")

3. 前端渲染展示

如果需要在页面上分类展示,可通过JavaScript渲染后端返回的分类数据。以下是HTML+JS示例:

<div class="questions-wrapper"></div>

<script>
// 模拟后端返回的分类题目数据
const categorizedQuestions = {
    easy: [{"id":2,"title":"两数之和"},{"id":4,"title":"字符串反转"}],
    medium: [{"id":1,"title":"数组求和"}],
    hard: [{"id":3,"title":"动态规划背包问题"}]
};

const wrapper = document.querySelector('.questions-wrapper');
const sortedLevels = ['easy', 'medium', 'hard'];

sortedLevels.forEach(level => {
    // 创建分类区块
    const section = document.createElement('div');
    section.className = `question-section ${level}`;
    section.innerHTML = `<h2>${level.charAt(0).toUpperCase() + level.slice(1)} 题目</h2>`;
    
    // 创建题目列表
    const list = document.createElement('ul');
    categorizedQuestions[level].forEach(q => {
        const item = document.createElement('li');
        item.textContent = `${q.id}. ${q.title}`;
        list.appendChild(item);
    });
    
    section.appendChild(list);
    wrapper.appendChild(section);
});
</script>

内容的提问来源于stack exchange,提问作者TAN CHIACHUN369

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 16:40:16