Python中如何动态迭代字符串或接收用户输入实现批次菜品轮转输出
Python菜品轮转序列生成实现
基础实现(匹配题目给定初始参数)
直接通过列表切片实现轮转逻辑,运行后输出结果和题目要求完全一致:
# 初始变量定义 number_of_batches = 8 number_of_dishes = 6 # 动态生成批次、菜品名称,无需手动逐个声明 batch_names = [f"batch_{i+1}" for i in range(number_of_batches)] dish_names = [f"dish_{i+1}" for i in range(number_of_dishes)] # 遍历生成每个批次的菜品序列 for idx, batch in enumerate(batch_names): # 计算偏移量,超过菜品总数时取模实现循环 offset = idx % number_of_dishes # 切片完成轮转:偏移位置后元素放前,偏移位置前元素接后 rotated_dishes = dish_names[offset:] + dish_names[:offset] # 按要求格式输出 print(f"{batch}: {', '.join(rotated_dishes)}")
支持用户自定义输入的通用实现
可以接收用户输入的批次数量、菜品数量,动态生成结果:
# 接收用户输入并做合法性校验 while True: try: number_of_batches = int(input("请输入批次数量:")) number_of_dishes = int(input("请输入菜品数量:")) if number_of_batches > 0 and number_of_dishes > 0: break print("请输入大于0的正整数") except ValueError: print("输入格式错误,请输入整数") # 动态生成名称 batch_names = [f"batch_{i+1}" for i in range(number_of_batches)] dish_names = [f"dish_{i+1}" for i in range(number_of_dishes)] # 生成并输出结果 for idx, batch in enumerate(batch_names): offset = idx % number_of_dishes rotated_dishes = dish_names[offset:] + dish_names[:offset] print(f"{batch}: {', '.join(rotated_dishes)}")
核心逻辑说明
- 用Python列表切片实现序列轮转是最简洁高效的方案,无需嵌套循环移动元素
- 偏移量取模
% number_of_dishes的逻辑,天然支持轮转完所有菜品后自动从头循环的需求 - 批次、菜品名称均为动态生成,可适配任意正整数的输入数量,无需手动修改变量定义
内容的提问来源于stack exchange,提问作者Sagar Nakade
相关产品推荐
相关产品推荐

