如何仅用循环从两个列表生成字典,不使用zip()、enumerate()等特殊函数
Python 纯循环实现双列表转指定规则字典
实现说明
完全使用基础循环逻辑,不依赖任何第三方库、也不使用zip_longest等特殊内置方法,符合要求。
完整实现代码
# 接收输入并预处理:按逗号分割后去除每个元素前后的空格 item_str = input("请输入物品名列表,多个用逗号分隔:") item_list = [item.strip() for item in item_str.split(',')] quantity_str = input("请输入数量列表,多个用逗号分隔:") quantity_list = [qty.strip() for qty in quantity_str.split(',')] res_dict = {} # 取两个列表的最大长度作为循环总次数 total_length = max(len(item_list), len(quantity_list)) for index in range(total_length): # 处理当前循环的键 if index < len(item_list): current_key = item_list[index] else: # 数量列表更长时,超出部分用默认键,序号从1开始递增 current_key = f'unknown object_{index - len(item_list) + 1}' # 处理当前循环的值 if index < len(quantity_list): current_value = quantity_list[index] else: # 物品名列表更长时,超出部分值默认为字符串格式的0,和示例格式一致 current_value = '0' res_dict[current_key] = current_value print("output :", res_dict)
效果验证
示例输入测试
输入物品名:Cans, bottles, boxes, jugs
输入数量:20,34,10
输出结果:{'Cans':'20','bottles':'34','boxes':'10','jugs':'0'},和要求的示例完全一致。
数量更长的场景测试
输入物品名:苹果,香蕉
输入数量:5,12,7,9
输出结果:{'苹果':'5','香蕉':'12','unknown object_1':'7','unknown object_2':'9'},符合规则要求。
内容的提问来源于stack exchange,提问作者Xflo
相关产品推荐
相关产品推荐

