哈喽各位小伙伴!这篇博客我100%还原自己从零编写「干饭随心选系统」的真实心路,没有跳步、没有晦涩术语,从“为啥想做这个项目”→“数据结构怎么从简陋变专业”→“每个函数怎么一步步写出来”→“主程序怎么搭”,全程复刻0-1编程过程。

一、项目初心:我为什么要写这个程序?

刚学Python字典+嵌套字典的时候,我总觉得知识点很抽象,背语法根本记不住。

刚好每天纠结“中午吃啥、晚上吃啥”,干脆做一个能查饭馆、智能推荐、筛选、增删改查的干饭小系统,既练手又实用!

我的核心需求很简单:

  1. 存下饭馆的类型、电话、菜单、价格、评分、营业时间

  2. 智能推荐,不重复吃最近3家店

  3. 按口味/价格/评分筛选饭馆

  4. 记录午餐、晚餐就餐历史

  5. 能添加、删除、修改饭馆信息

  6. 做成菜单式交互,用完不退出

就这样,「干饭随心选系统」正式开工!

二、第一步:搭数据结构(从0到1的核心起步)

写代码第一步永远是存数据,我最开始写得特别简陋,慢慢优化成专业的嵌套结构。

1. 菜鸟起步:单层字典(只能存名字+电话)

最开始我只会用单层字典,功能极度受限,存不下菜单、评分这些信息:

# ❶ 菜鸟版:只能存名称+电话,完全不够用
restaurants = {
    "川菜馆": "123-4567",
    "粤菜馆": "234-5678"
}

2. 进阶优化:嵌套字典+列表(完美存所有信息)

嵌套字典+列表是处理 “结构化多维度数据” 的核心方式,比如 “饭馆” 作为一个实体,包含多个属性,用内层字典封装更清晰;列表适合存储 “有序的序列数据”(如历史记录、菜单),字典适合存储 “键值对的映射数据”(如饭馆属性)。

我突然想通:一家饭馆=多个属性,用「字典套字典」最合适,菜单用列表存多道菜,历史记录用列表存顺序,最终定稿:

# 干饭随心选系统

print("\n\n=== 干饭随心选系统 ===")

# 使用字典存储更详细的饭馆信息
restaurants_dict = {
    "川菜馆": {
        "类型": "川菜",
        "电话": "123-4567",
        "菜单": ["麻婆豆腐", "水煮鱼", "宫保鸡丁", "回锅肉"],
        "价格区间": "中等",
        "评分": 4.5,
        "营业时间": "11:00-22:00"
    },
    "粤菜馆": {
        "类型": "粤菜",
        "电话": "234-5678",
        "菜单": ["白切鸡", "烧鹅", "叉烧", "虾饺"],
        "价格区间": "偏高",
        "评分": 4.3,
        "营业时间": "10:30-21:30"
    },
    "湘菜馆": {
        "类型": "湘菜",
        "电话": "345-6789",
        "菜单": ["剁椒鱼头", "毛氏红烧肉", "辣椒炒肉"],
        "价格区间": "中等",
        "评分": 4.2,
        "营业时间": "11:00-23:00"
    },
    "日料店": {
        "类型": "日料",
        "电话": "456-7890",
        "菜单": ["寿司拼盘", "刺身", "拉面", "天妇罗"],
        "价格区间": "偏高",
        "评分": 4.7,
        "营业时间": "11:30-22:00"
    },
    "西餐厅": {
        "类型": "西餐",
        "电话": "567-8901",
        "菜单": ["牛排", "意大利面", "沙拉", "披萨"],
        "价格区间": "偏高",
        "评分": 4.4,
        "营业时间": "11:00-23:00"
    },
    "火锅店": {
        "类型": "火锅",
        "电话": "678-9012",
        "菜单": ["麻辣火锅", "清汤火锅", "鸳鸯锅"],
        "价格区间": "中等",
        "评分": 4.6,
        "营业时间": "10:00-24:00"
    }
}


# 历史选择记录
lunch_history = []
dinner_history = []

初级阶段:如果是新手入门,可能先只用 “单层字典” 存储基础信息,比如 restaurants = {"川菜馆": "123-4567", "粤菜馆": "234-5678"},只能存 “名称 - 电话”,无法承载多维度信息。

进阶阶段:采用 “嵌套字典 + 列表” 的结构化设计:

  • 外层字典:key=饭馆名称,value=该饭馆的所有信息(内层字典),实现 “按名称快速查找”;
  • 内层字典:key=信息维度(类型/电话/菜单等),value=对应值,其中 “菜单” 用列表存储多菜品,适配 “多个值” 的场景;
  • 历史记录:用列表 lunch_history = [ ] 、dinner_history = [ ] 存储,利用列表 “有序、可重复、支持 append/remove” 的特性,记录选择顺序。

三、第二步:拆分功能,逐写函数(核心代码全保留+逐行解析)

我遵循一个函数只做一件事,把所有功能拆成8个函数,从零开始写,每一步都优化体验。

  • 函数模块整体设计思路:所有函数遵循 “单一职责原则”—— 一个函数只做一件事。
  • 功能点:增删改查

(一)展示所有饭馆函数:遍历嵌套字典

我的思考

要把所有饭馆的信息完整打印出来,用items()遍历嵌套字典最方便。

  • 查询饭馆信息
def show_all_restaurants():
    """显示所有饭馆详细信息"""
    print("\n所有饭馆详细信息:")
    for name, info in restaurants_dict.items():
        print(f"\n{name}:")
        print(f"  类型: {info['类型']}")
        print(f"  电话: {info['电话']}")
        print(f"  菜单: {', '.join(info['菜单'])}")
        print(f"  价格: {info['价格区间']}")
        print(f"  评分: {info['评分']}")
        print(f"  营业时间: {info['营业时间']}")

(二)修改饭馆函数:回车保留原值(超实用优化)

我的思考

一开始修改必须全填,太麻烦!用input() or 原值实现回车保留原值,体验直接拉满。

  • 修改饭馆详情
def modify_restaurant():
    """修改饭馆信息"""
    print("\n修改饭馆信息:")
    
    # 先显示所有饭馆供用户选择
    if not restaurants_dict:
        print("当前系统中没有饭馆信息!")
        return
    
    print("当前系统中的饭馆:")
    for i, name in enumerate(restaurants_dict.keys(), 1):
        print(f"{i}. {name}")
    
    restaurant_name = input("\n请输入要修改的饭馆名称: ")
    
    if restaurant_name in restaurants_dict:
        print(f"\n当前 {restaurant_name} 的信息:")
        info = restaurants_dict[restaurant_name]
        print(f"类型: {info['类型']}")
        print(f"电话: {info['电话']}")
        print(f"菜单: {', '.join(info['菜单'])}")
        print(f"价格区间: {info['价格区间']}")
        print(f"评分: {info['评分']}")
        print(f"营业时间: {info['营业时间']}")
        
        print("\n请输入新的信息(直接回车保持原值):")
        
        new_type = input(f"类型 [{info['类型']}]: ") or info['类型']
        new_phone = input(f"电话 [{info['电话']}]: ") or info['电话']
        new_menu_input = input(f"菜单 [{', '.join(info['菜单'])}]: ")
        new_menu = new_menu_input.split(",") if new_menu_input else info['菜单']
        new_price = input(f"价格区间 [{info['价格区间']}]: ") or info['价格区间']
        
        new_score_input = input(f"评分 [{info['评分']}]: ")
        new_score = float(new_score_input) if new_score_input else info['评分']
        
        new_hours = input(f"营业时间 [{info['营业时间']}]: ") or info['营业时间']
        
        # 更新信息
        restaurants_dict[restaurant_name] = {
            "类型": new_type,
            "电话": new_phone,
            "菜单": new_menu,
            "价格区间": new_price,
            "评分": new_score,
            "营业时间": new_hours
        }
        
        print(f"成功更新 {restaurant_name} 的信息!")
    else:
        print(f"未找到名为 {restaurant_name} 的饭馆!")

(三)删除饭馆函数:单个+批量删除+同步清历史

我的思考

新手容易直接删,我加了确认提示、空值判断、同步删除历史,防止误操作,还做了批量删除功能。

  • .删除现有饭馆
def delete_restaurant():
    """删除饭馆"""
    print("\n删除饭馆:")
    
    # 先显示所有饭馆供用户选择
    if not restaurants_dict:
        print("当前系统中没有饭馆信息!")
        return
    
    print("\n删除方式:")
    print("1. 按名称删除单个饭馆")
    print("2. 按条件批量删除")
    
    delete_choice = input("请选择删除方式(1-2): ")
    
    if delete_choice == "1":
        # 单个删除逻辑
        print("\n当前系统中的饭馆:")
        for i, name in enumerate(restaurants_dict.keys(), 1):
            print(f"{i}. {name}")
        
        restaurant_name = input("\n请输入要删除的饭馆名称: ")
        
        if restaurant_name in restaurants_dict:
            # 确认删除
            confirm = input(f"确定要删除 {restaurant_name} 吗?(y/n): ")
            if confirm.lower() == 'y':
                del restaurants_dict[restaurant_name]
                print(f"成功删除 {restaurant_name}!")
                
                # 同时从历史记录中删除
                if restaurant_name in lunch_history:
                    lunch_history.remove(restaurant_name)
                if restaurant_name in dinner_history:
                    dinner_history.remove(restaurant_name)
            else:
                print("取消删除操作")
        else:
            print(f"未找到名为 {restaurant_name} 的饭馆!")
    
    elif delete_choice == "2":
        # 批量删除逻辑(这里需要倒序遍历)
        print("\n批量删除条件:")
        print("1. 按类型删除")
        print("2. 按价格区间删除")
        print("3. 按评分删除")
        
        batch_choice = input("请选择批量删除条件(1-3): ")
        
        restaurants_to_delete = []
        
        if batch_choice == "1":
            type_filter = input("请输入要删除的类型(川菜/粤菜/湘菜/日料/西餐/火锅): ")
            restaurants_to_delete = [name for name, info in restaurants_dict.items() 
                                    if info['类型'] == type_filter]
        
        elif batch_choice == "2":
            price_filter = input("请输入要删除的价格区间(中等/偏高): ")
            restaurants_to_delete = [name for name, info in restaurants_dict.items() 
                                    if info['价格区间'] == price_filter]
        
        elif batch_choice == "3":
            max_score = float(input("请输入最高评分(删除评分低于此值的饭馆): "))
            restaurants_to_delete = [name for name, info in restaurants_dict.items() 
                                    if info['评分'] <= max_score]
        
        else:
            print("无效选择")
            return
        
        if not restaurants_to_delete:
            print("没有找到符合条件的饭馆!")
            return
        
        print(f"\n找到 {len(restaurants_to_delete)} 家符合条件的饭馆:")
        for i, name in enumerate(restaurants_to_delete, 1):
            print(f"{i}. {name}")
        
        confirm = input(f"\n确定要删除这 {len(restaurants_to_delete)} 家饭馆吗?(y/n): ")
        if confirm.lower() == 'y':
            # 这里需要倒序遍历列表来安全删除
            deleted_count = 0
            for i in range(len(restaurants_to_delete)-1, -1, -1):
                name = restaurants_to_delete[i]
                del restaurants_dict[name]
                
                # 同时从历史记录中删除
                if name in lunch_history:
                    lunch_history.remove(name)
                if name in dinner_history:
                    dinner_history.remove(name)
                
                deleted_count += 1
                print(f"已删除: {name}")
            
            print(f"\n成功批量删除 {deleted_count} 家饭馆!")
        else:
            print("取消批量删除操作")
    
    else:
        print("无效选择")

(四)添加饭馆函数:接收用户输入动态添加

我的思考

支持用户手动输入所有信息,菜单用split()拆分逗号分隔的菜品,评分转浮点型。

  • 添加新饭馆信息
def add_new_restaurant():
    """添加新饭馆"""
    print("\n添加新饭馆:")
    name = input("饭馆名称: ")
    type_ = input("饭馆类型: ")
    phone = input("联系电话: ")
    menu = input("菜单(用逗号分隔): ").split(",")
    price = input("价格区间(中等/偏高): ")
    score = float(input("评分(0-5): "))
    hours = input("营业时间: ")
    
    restaurants_dict[name] = {
        "类型": type_,
        "电话": phone,
        "菜单": menu,
        "价格区间": price,
        "评分": score,
        "营业时间": hours
    }
    print(f"成功添加 {name} 到系统!")

(五)智能推荐函数:避免重复吃饭(核心亮点)

+  智能选餐函数:调用推荐+展示信息+记录历史

我的思考

一开始只想随机推荐,但是会重复吃同一家,体验太差!于是加了「排除最近3次就餐」逻辑,还要考虑「全吃过」的兜底情况。并且推荐完要展示完整信息,还要把店名加入历史记录,形成选餐→展示→记录闭环。

  • 智能推荐
    • 防重复机制:避免连续推荐同一饭馆
    • 根据时间(午餐/晚餐)自动推荐饭馆
def smart_recommendation(meal_type, history):
    """智能推荐饭馆,避免重复选择"""
    import random
    
    # 获取所有饭馆名称
    all_restaurants = list(restaurants_dict.keys())
    
    # 如果历史记录为空,随机选择
    if not history:
        return random.choice(all_restaurants)
    
    # 避免最近选择的饭馆
    recent_choices = history[-3:]  # 最近3次选择
    available_choices = [r for r in all_restaurants if r not in recent_choices]
    
    # 如果所有饭馆都在最近选择过,则从所有中选择
    if not available_choices:
        available_choices = all_restaurants
    
    return random.choice(available_choices)

def select_meal(meal_type, history):
    """智能选择餐食(午餐/晚餐)"""
    selected_name = smart_recommendation(meal_type, history)
    selected_info = restaurants_dict[selected_name]
    
    history.append(selected_name)
    
    print(f"\n{meal_type}智能推荐: {selected_name}")
    print(f"类型: {selected_info['类型']}")
    print(f"电话: {selected_info['电话']}")
    print(f"推荐菜单: {', '.join(selected_info['菜单'])}")
    print(f"价格区间: {selected_info['价格区间']}")
    print(f"评分: {selected_info['评分']}")
    print(f"营业时间: {selected_info['营业时间']}")
  •  查看历史记录
    • 提供历史数据查询功能
    • 记录用户访问和推荐历史
def show_selection_history():
    """显示选择历史"""
    print("\n午餐选择历史:")
    for i, restaurant in enumerate(lunch_history, 1):
        print(f"{i}. {restaurant}")
    
    print("\n晚餐选择历史:")
    for i, restaurant in enumerate(dinner_history, 1):
        print(f"{i}. {restaurant}")

(六)筛选函数:按类型/价格/评分筛选

我的思考

用户有不同需求,做3种筛选方式,用字典推导式快速过滤,无结果时给提示。

  • 按条件筛选
    • 支持按菜系、价格、评分等条件筛选
def filter_restaurants():
    """按条件筛选饭馆"""
    print("\n筛选条件:")
    print("1. 按类型筛选")
    print("2. 按价格筛选")
    print("3. 按评分筛选")
    
    filter_choice = input("请选择筛选方式(1-3): ")
    
    if filter_choice == "1":
        type_filter = input("请输入类型(川菜/粤菜/湘菜/日料/西餐/火锅): ")
        filtered = {name: info for name, info in restaurants_dict.items() 
                   if info['类型'] == type_filter}
    
    elif filter_choice == "2":
        price_filter = input("请输入价格区间(中等/偏高): ")
        filtered = {name: info for name, info in restaurants_dict.items() 
                   if info['价格区间'] == price_filter}
    
    elif filter_choice == "3":
        min_score = float(input("请输入最低评分(0-5): "))
        filtered = {name: info for name, info in restaurants_dict.items() 
                   if info['评分'] >= min_score}
    
    else:
        print("无效选择")
        return
    
    if filtered:
        print(f"\n找到 {len(filtered)} 家符合条件的饭馆:")
        for name, info in filtered.items():
            print(f"{name}: {info['类型']}, 评分{info['评分']}, 价格{info['价格区间']}")
    else:
        print("未找到符合条件的饭馆")
  • 四、第三步:搭主程序循环(菜单式交互,用完不退出)

    我的思考

    一开始没有循环,用一次就退出,太不方便!用while True永久循环,做9个菜单选项,输错给提示,完美模拟APP交互。

  • 菜单式循环交互
    • 主菜单选项:
      • 查看饭馆信息
      • 智能推荐(午餐/晚餐)
      • 按条件筛选
      • 查看历史记录
      • 管理饭馆(添加、删除、修改)
      • 退出系统
    • 循环逻辑:用户选择后返回菜单,直至退出
# 主程序循环
while True:
    print("\n" + "="*60)
    print("欢迎使用干饭随心选系统")
    print("1. 查看所有饭馆详细信息")
    print("2. 智能选择午餐(避免重复)")
    print("3. 智能选择晚餐(避免重复)")
    print("4. 按条件筛选")
    print("5. 查看选择历史")
    print("6. 添加新饭馆")
    print("7. 删除饭馆")
    print("8. 修改饭馆信息")
    print("9. 退出系统")
    
    choice = input("请选择功能(1-9): ")
    
    if choice == "1":
        show_all_restaurants()
    
    elif choice == "2":
        select_meal("午餐", lunch_history)
    
    elif choice == "3":
        select_meal("晚餐", dinner_history)
    
    elif choice == "4":
        filter_restaurants()
    
    elif choice == "5":
        show_selection_history()
    
    elif choice == "6":
        add_new_restaurant()
    
    elif choice == "7":
        delete_restaurant()
    
    elif choice == "8":
        modify_restaurant()
    
    elif choice == "9":
        print("感谢使用干饭随心选系统,再见!")
        break
    
    else:
        print("无效选择,请重新输入(1-9)")

五、零基础复刻总结:我的核心收获

  1. 数据结构是核心:嵌套字典+列表,能搞定90%的小型管理系统数据存储

  2. 函数化编程:一个函数做一件事,代码不乱、好修改、好复用

  3. 用户体验最重要:回车保留原值、删除确认、无效提示,这些小细节让程序更专业

  4. 通用套路:存数据→拆功能→写函数→搭循环→测优化,所有管理系统都能这么做

这个项目全程是我从零敲代码的真实心路,没有任何花里胡哨的技巧,新手跟着步骤走,复制代码就能运行,改改数据就能做成图书管理、学生管理、任务管理系统!

Logo

小龙虾开发者社区是 CSDN 旗下专注 OpenClaw 生态的官方阵地,聚焦技能开发、插件实践与部署教程,为开发者提供可直接落地的方案、工具与交流平台,助力高效构建与落地 AI 应用

更多推荐